接收新道具时状态不更新(ReactJS)

Ire*_* Li 9 reactjs

我是React的新手.我坚持这个,真的很感激一些帮助!

父组件将数组传递给此子组件.当我在console.log(this.props.repairs)时,它向我显示了一个4的数组.每当传入修复数组时,我都会尝试更新this.state.sortedDataList.控制台.log(this.state)仍然是将sortedDataList显示为空数组.

我究竟做错了什么?非常感谢,感谢任何帮助.

class Repairs extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      sortedDataList: []
    };
  }

  componentWillReceiveProps(nextProps) {
    if(this.props != nextProps) {
      this.setState({
        sortedDataList: this.props.repairs
      });
    }
  }

  render() {
    console.log(this.props);
    console.log(this.state);

    return (
      <div></div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ire*_* Li 5

没关系,发现了我愚蠢的错误!如果将来还有其他人陷入困境...

componentWillReceiveProps(nextProps) {
  if(this.props != nextProps) {
    this.setState({
      sortedDataList: nextProps.repairs
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 总而言之,问题是使用当前道具而不是下一个道具调用setState。 (3认同)

Shu*_*tri 3

componentWillReceiveProps第一次渲染时不会被调用。这就是您在状态中看不到任何更新的原因

来自反应文档

“当组件接收新的道具时调用。初始渲染不会调用此方法。”

如果您只想第一次进行更改,您可以使用componentWillMount生命周期函数并更新状态。在随后的更改中,您的 componentWillReceiveProps 将被调用。

class Repairs extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      sortedDataList: []
    };
  }

  componentWillMount() {
   
      this.setState({
        sortedDataList: this.props.repairs
      }, () => console.log(this.state.sortedDataList));
    
  }
   componentWillReceiveProps(nextProps) {
    if(this.props != nextProps) {
      this.setState({
        sortedDataList: nextProps.repairs
      });
    }
  }

  render() {
    console.log("r",this.props);
    console.log("r",this.state);

    return (
      <div></div>
    );
  }
}

class App extends React.Component {
  render() {
    var arr = ["1", "2", "3"];
    return (
      <div >
        <Repairs repairs={arr}/>
      </div>
    )
  }
}
ReactDOM.render(<App/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)