提问者:小点点

父级状态更改后不更新子级组件


我正在尝试制作一个很好的ApiWrapper组件来填充各种子组件中的数据。从我读到的所有内容来看,这应该是可行的:https://jsfidle.net/vinniejames/m1mesp6z/1/

class ApiWrapper extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      response: {
        "title": 'nothing fetched yet'
      }
    };
  }

  componentDidMount() {
    this._makeApiCall(this.props.endpoint);
  }

  _makeApiCall(endpoint) {
    fetch(endpoint).then(function(response) {
      this.setState({
        response: response
      });
    }.bind(this))
  }

  render() {
    return <Child data = {
      this.state.response
    }
    />;
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: props.data
    };
  }

  render() {
    console.log(this.state.data, 'new data');
    return ( < span > {
      this.state.data.title
    } < /span>);
  };
}

var element = < ApiWrapper endpoint = "https://jsonplaceholder.typicode.com/posts/1" / > ;

ReactDOM.render(
  element,
  document.getElementById('container')
);

但由于某种原因,当父状态更改时,子组件似乎没有更新。

我是不是漏了什么?


共2个答案

匿名用户

您的代码有两个问题。

子组件的初始状态是从props设置的。

this.state = {
  data: props.data
};

引用这个SO回答:

将初始状态作为prop传递给组件是一种反模式,因为getInitialState(在本例中是constuctor)方法只在组件第一次呈现时才被调用。再也不会了。这意味着,如果您将传递不同值的组件作为prop重新呈现,组件将不会做出相应的反应,因为组件将保持第一次呈现时的状态。很容易出错。

因此,如果无法避免这种情况,理想的解决方案是使用componentwillreceiveprops方法来侦听新的props。

向子组件添加下面的代码将解决子组件重新呈现的问题。

componentWillReceiveProps(nextProps) {
  this.setState({ data: nextProps.data });  
}

第二个问题是fetch

_makeApiCall(endpoint) {
  fetch(endpoint)
    .then((response) => response.json())   // ----> you missed this part
    .then((response) => this.setState({ response }));
}

下面是一个工作小提琴:https://jsfidle.net/o8b04mly/

匿名用户

有些事情你需要改变。

fetch获得响应时,它不是一个JSON。我正在寻找如何获得这个json,我发现了这个链接。

另一方面,您需要认为constructor函数只被调用一次。

因此,您需要更改在组件中检索数据的方式。

在这里,我留下了一个示例代码:https://jsfidle.net/emq1ztqj/

希望这能帮上忙。