繁体   English   中英

如何在反应中使用 lifeCyle 和 setState?

[英]How to use lifeCyle and setState in react?

这是 app.js

class App extends Component {
  constructor() {
    super();
    this.state = {
      todo_lists: [
        { id: 1, name: "Hoc React" },
        { id: 2, name: "Hoc HTML" },
        { id: 3, name: "Hoc Jquery" },
        { id: 4, name: "Hoc CSS" }
      ],
      showList : []
    };
  }
  componentDidMount(){
    let {showList, todo_lists} = this.state
  this.setState({
    showList : [...todo_lists]
  })
  console.log(showList)
  }
}

当浏览器上的 console.log(showList) 返回像这样 [] 的空数组时,显然我在 setState 中分配了 showList: [...todo_lists]。 帮我

问题:

// this.setState is async method
this.setState({
    showList : [...todo_lists]
}); 
console.log(showList) // <--- this will not give you updated value right after

您可以为此使用this.setState callback方法,在设置 state 后立即调用它

this.setState({
    // showList : [...todo_lists]
    showList : this.state.todo_lists.map(todo => ({ ...todo}))
},() => {
    console.log(this.state.showList) //<------ Check here
})

建议:

constructor() {
    super();
    this.todos = [
        { id: 1, name: "Hoc React" },
        { id: 2, name: "Hoc HTML" },
        { id: 3, name: "Hoc Jquery" },
        { id: 4, name: "Hoc CSS" }
    ]
    this.state = {
      todo_lists: this.todos.map(todo => ({ ...todo})),
      showList : this.todos.map(todo => ({...todo}))
    };
}

来自 Reactjs.org

将 setState() 视为更新组件的请求而不是立即命令。 为了更好地感知性能,React 可能会延迟它,然后一次更新多个组件。 React 不保证立即应用 state 更改。

https://reactjs.org/docs/react-component.html#setstate

因此,您所写的内容不会立即发生,并且您的 console.log 不会立即获得正确的值。

这里的问题是 React 的 setState 是一个异步方法,因此它可能会延迟更新以有利于感知性能的提高。

可以做的是这样的(如果你不想使用 setState 提供的回调)

componentDidMount() {

  const {showList, todo_lists} = this.state,
    nextShowList = [...todo_lists];

  this.setState({
    showList: nextShowList
  });

  console.log(nextShowList); // executes immediatelly

}

如果使用 setState 方法提供的回调,只需像这样使用它:

componentDidMount() {

   const {showList, todo_lists} = this.state;

   this.setState({
     showList: [...todo_lists]
   }, () => console.log(this.state.showList)); // MAY NOT execute immediately

}

另外,作为一个额外的提示(如果我可以的话),将第一个参数用作 function,否则您可能在设置 todo_list 时遇到问题!

componentDidMount() {

  this.setState(prevState => {

    return {
      showList: [...prevState.todo_lists]
    };

  }, () => console.log(this.state.showList));

}

同样,出于同样的原因:由于 setState 是异步的,因此您不能保证 setState之外的 this.state 是最新的!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM