Reactjs 如何解决在onClick事件之后工作一步的状态更改问题
我想通过点击改变状态,但它的工作落后一步。我不明白出了什么问题Reactjs 如何解决在onClick事件之后工作一步的状态更改问题,reactjs,Reactjs,我想通过点击改变状态,但它的工作落后一步。我不明白出了什么问题 class Products extends Component { state = { product: null } render() { const handalebar = (event) => { event.preventDefault(); const produ
class Products extends Component {
state = {
product: null
}
render() {
const handalebar = (event) => {
event.preventDefault();
const product_code = event.target.closest('.card').getAttribute('id');
this.setState({
product: product_code
})
console.log(this.state.product);
}
setState是异步的,请使用回调记录更新的状态:
setState(
{ product: product_code },
() => console.log(this.state.product)
);
我认为应该在render函数之外编写handlebar函数,并将state对象放入构造函数中,不要忘记绑定函数
class Products extends Component{
constructor(props){
super(props)
this.state = {
product: null
}
this.handlebar = this.handlebar.bind(this);
}
handlebar = (event) => {
event.preventDefault();
const product_code = event.target.value;
this.setState({
product: product_code
})
render(){
console.log(this.state.product);
return (
<div>
</div>
)
}
}
类产品扩展组件{
建造师(道具){
超级(道具)
此.state={
产品:空
}
this.handlebar=this.handlebar.bind(this);
}
车把=(事件)=>{
event.preventDefault();
const product_code=event.target.value;
这是我的国家({
产品:产品代码
})
render(){
console.log(this.state.product);
返回(
)
}
}
您需要包含一个完整的示例。在上面的代码中,产品代码
尚未定义,车把
未被使用,并且您的渲染
函数不会返回任何内容。为什么要使用箭头函数并将其绑定到ctor中?您到底想要什么?我想知道为什么要绑定箭头函数激动。