gpt4 book ai didi

javascript - ReactJS setState 不适用于复选框的第一个切换

转载 作者:行者123 更新时间:2023-11-30 15:49:00 26 4
gpt4 key购买 nike

有什么原因 setState 不会运行重新渲染?我使用了 console.log 回调来检测状态是否已更改,但无济于事。

这是我正在使用的代码。还有更多这样的状态是函数调用的 bool,但函数的基础知识在这里。

export class ExampleClass extends React.Component {
constructor(props) {
super(props);
this.state = {
usingToggleOne: false
};
}
}
toggleforToggleOne(event) {
this.setState({
usingToggleOne: !this.state.usingToggleOne,
});
}

render() {
return(
<input type="checkbox"
onChange={this.toggleforToggleOne.bind(this)} />
}

我会第一次点击复选框,它会打勾,但状态不会改变,但之后它会正常工作。有什么理由吗?我很幸运地使用 Object.assign 让第一个滴答开始工作,但我宁愿不使用它,因为它会改变状态。

最佳答案

render()componentDidUpdate() 方法中尝试 console.log(),如下面的代码和这个代码笔:http://codepen.io/PiotrBerebecki/pen/ZpLNZd

您还可以使用传递给“setState”的可选回调函数访问新状态。更多信息在这里:http://reactkungfu.com/2016/03/dive-into-react-codebase-handling-state-changes/#solving_the_validation_problem

状态 bool 每次勾选/取消勾选时都会改变。

此外,请注意 React 文档中的以下内容:https://facebook.github.io/react/docs/component-api.html#setstate

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

class ExampleClass extends React.Component {
constructor() {
super();
this.state = {
usingToggleOne: false
};

}

toggleforToggleOne(event) {
console.clear();
console.log('check in toggle before set state', this.state.usingToggleOne);
this.setState({
usingToggleOne: !this.state.usingToggleOne
}, function afterStateChange () {this.useNewState();});
console.log('check in toggle after set state', this.state.usingToggleOne);
}

useNewState() {
console.log('check in useNewState callback', this.state.usingToggleOne);
}

componentWillUpdate() {
console.log('check in componentWillUpdate', this.state.usingToggleOne);
}

componentDidUpdate() {
console.log('check in componentDidUpdate', this.state.usingToggleOne);
}

render() {
console.log('check in render', this.state.usingToggleOne);
return(
<input type="checkbox"
onChange={this.toggleforToggleOne.bind(this)} />
);
}
}

关于javascript - ReactJS setState 不适用于复选框的第一个切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com