react--setState使用
(一)使用注意事项 1,不要直接修改state 2,state的更新可能是异步的(出于性能考虑,React 可能会把多个? 3,state的更新会被合并(当你调用? (二)react异步更新带来的问题解决方案 1,当需要在state的一些状态来改变之后做一些事情时,由于会出现异步更新会很麻烦 1---传入回调函数 setState({ index: 1 }},function(){ console.log(this.state.index); }) 2---通过es6的async和await解决 (三)setState的另一种使用方式(需要使用上一次的state值) 在setState的第一个参数中传入function,该function会被压入调用栈中,在state真正改变后,按顺序回调栈里面的function。该function的第一个参数为上一次更新后的state。这样就能确保你下一次的操作拿到的是你预期的值 class Com extends React.Component{ constructor(props){ super(props); this.state = { index: 0 } this.add = this.add.bind(this); } add(){ this.setState(prevState => { return {index: prevState.index + 1}; }); this.setState(prevState => { return {index: prevState.index + 1}; }); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |