简体   繁体   English

反应:动态创建 state 变量

[英]React: Dynamically created state variable

I tried to run the code below, but I got an undefined from the console.log statement.我试图运行下面的代码,但我从console.log语句中得到一个undefined的。 Any thoughts?有什么想法吗?

this.setState({ [show]: true })
console.log("this.state.show: " , this.state.show);

In your code you don't set state exactly for show.在您的代码中,您没有设置 state 完全用于展示。 Example:例子:

const show = 'light';
this.setState({[show]: false}) // you set state for 'light'(this.state.light: false)

If you don't set variable show before, you should use:如果您之前没有设置变量显示,您应该使用:

this.setState({ show: true })

And if you need to get state right after setting:如果您需要在设置后立即获得 state:

this.setState({ show: true }, () => console.log("this.state.show: " , this.state.show);)

If you are trying to check if state did update the best way to do that is simply to check for it inside the render() function, because the component is always re-rendered when you update the state.如果您要检查 state 是否确实更新了,最好的方法就是在render() function 中检查它,因为当您更新 Z9ED39E2EA934286B6A9857A 时,组件总是会重新渲染。 This would probably look like this (I have added a ternary operation as an example of how you can show and hide your component):这可能看起来像这样(我添加了一个三元运算作为如何显示和隐藏组件的示例):

render(){
  console.log(this.state.show);
  return this.state.show ? <MyComponent /> : null;
}

But if you really want to check if the state changed just after using the setState function, for example inside another function (and not render() ), you will need to call console.log inside a callback.但是,如果你真的想检查 state 是否在使用setState function 之后发生了变化,例如在另一个 function 内部(而不是在console.log中调用render()将需要调用回调)。 This is because state takes some time to update and therefore synchronous code would fail.这是因为 state 需要一些时间来更新,因此同步代码会失败。 setState takes callback functions as a second parameter. setState将回调函数作为第二个参数。 So, you can just re-write like this:所以,你可以像这样重写:

this.setState({ show: true }, () => console.log("this.state.show: " , this.state.show));

Hope that helped...希望有帮助...

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

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