简体   繁体   English

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

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

this is app.js这是 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)
  }
}

when console.log(showList) on browser it return empty array like this [], clearly I assigned showList: [...todo_lists] in setState.当浏览器上的 console.log(showList) 返回像这样 [] 的空数组时,显然我在 setState 中分配了 showList: [...todo_lists]。 help me帮我

Issue:问题:

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

you can use this.setState callback method for that, it is being called right after the state is set您可以为此使用this.setState callback方法,在设置 state 后立即调用它

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

Suggestion:建议:

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}))
    };
}

From Reactjs.org来自 Reactjs.org

Think of setState() as a request rather than an immediate command to update the component.将 setState() 视为更新组件的请求而不是立即命令。 For better perceived performance, React may delay it, and then update several components in a single pass.为了更好地感知性能,React 可能会延迟它,然后一次更新多个组件。 React does not guarantee that the state changes are applied immediately. React 不保证立即应用 state 更改。

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

So what you wrote will NOT happen immediately, and your console.log will NOT get the right values immediately afterwards.因此,您所写的内容不会立即发生,并且您的 console.log 不会立即获得正确的值。

The problem here is that React's setState is an async method, so it may delay the update in favor of perceived improvement in performance.这里的问题是 React 的 setState 是一个异步方法,因此它可能会延迟更新以有利于感知性能的提高。

What you could do, is something like this (if you don't want to use the callback provided by the setState) :可以做的是这样的(如果你不想使用 setState 提供的回调)

componentDidMount() {

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

  this.setState({
    showList: nextShowList
  });

  console.log(nextShowList); // executes immediatelly

}

If you want to use the callback provided by the setState method, simply use it like this:如果使用 setState 方法提供的回调,只需像这样使用它:

componentDidMount() {

   const {showList, todo_lists} = this.state;

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

}

Also, as an additional tip (if I may), use the first argument as a function, or you may have problems setting your todo_list!另外,作为一个额外的提示(如果我可以的话),将第一个参数用作 function,否则您可能在设置 todo_list 时遇到问题!

componentDidMount() {

  this.setState(prevState => {

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

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

}

Again, for the same reason: Since setState is async, you can't guarantee that the this.state outside of the setState is up-to-date!同样,出于同样的原因:由于 setState 是异步的,因此您不能保证 setState之外的 this.state 是最新的!

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

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