因此,我正在尝试使用以前的状态来更改状态,但是无论如何都不会更改。谁能告诉我问题出在哪里吗?
handleToggleComplete = (key, complete) => {
itemIndex = this.state.items.findIndex(item => item.key === key);
console.log('before: ', this.state.items);
this.setState(prevState => {
return {
...prevState,
items: [
...prevState.items,
prevState.items[itemIndex]: {
completed: true,
text: 'hardcoded value'
}
]
}
});
console.log('after: ', this.state.items);
}
日志:
before:
[{…}]
{key: 1530370127933, completed: false, text: "some value"}
after:
[{…}]
{key: 1530370127933, completed: false, text: "some value"}
答案 0 :(得分:1)
return START_STICKY
不会立即更改状态。它重新渲染组件并具有更新的状态。因此,自然不会在函数中看到更新状态。
这是一个演示了这一点的应用程序。我在控制台中显示了状态的当前值,并使用按钮进行渲染:
this.setState
class App extends React.Component {
constructor (props) {
super(props)
this.state = {
myState: 0
}
}
handleClick () {
let incrementState = this.state.myState + 1
console.log('State before increment:', this.state.myState)
this.setState({myState: incrementState})
console.log('State AFTER increment:', this.state.myState, '\nSee, it\'s still the same BUT the component has been updated (look at the number)!')
}
render() {
const { myState } = this.state
return (<div>
<h1>{myState}</h1>
<button onClick={() => this.handleClick()}>Increment State</button>
</div>);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);