[英]Should values ever be stored on the instance of a component?
Can I ever do something like this? 我可以做这样的事情吗? Does it avoid issues with asynchronous state changes? 是否可以避免异步状态更改带来的问题?
class Widget extends React.Component {
constructor () {
this.value = '123';
}
render () {
var hello = this.value;
// ...
}
}
Yes you can use Class properties to store data, and you can use that in render method. 是的,您可以使用Class属性存储数据,并且可以在render方法中使用它。 For eg: constants 例如:常量
But you will have to use state to store data that directly affects how a component is rendered, and use setState function to update state as this triggers component re-render. 但是您将必须使用状态来存储直接影响组件呈现方式的数据,并使用setState函数来更新状态,因为这会触发组件重新呈现。 Setting data in simple class property wont re-render component. 在简单类属性中设置数据不会重新渲染组件。
Does it avoid issues with asynchronous state changes?
No. after your asynchronous operation, for eg: an ajax api fetch, if you are simply setting this.data = fetchedData
ReactDom wont know that new data has arrived and it should re render the component. 否。在异步操作之后,例如:ajax api fetch,如果您只是简单地设置this.data = fetchedData
ReactDom将不知道新数据已经到达,应该重新呈现组件。 But if you are using setState there it will know and it can trigger all the needed lifecycle methods and render method. 但是,如果您使用setState,它将知道并且可以触发所有必需的生命周期方法和render方法。
Can I ever do something like this? 我可以做这样的事情吗?
Yes sure. 是的
Does it avoid issues with asynchronous state changes? 是否可以避免异步状态更改带来的问题?
No, indeed it makes things worse. 不,确实会使情况更糟。 For state changes, use setState
! 对于状态更改,请使用setState
!
class Widget extends React.Component { constructor () { this.state = { value: '123' } } render () { var hello = this.state.value; // ... } }
Yes you can do that. 是的,你可以这么做。 But whenever the value will be changed like 但是每当值改变时
this.value = "newValue" this.value =“ newValue”
the changes will not be reflected in the VIEW as render() will not be called by this. 所做的更改将不会在VIEW中反映出来,因为render()不会被此方法调用。
You can just set the state for viewing this change instantly by setting a random id change in state like 您可以通过设置状态的随机id更改来设置状态以立即查看此更改
this.value = "newValue";
this.setState({id:Math.random()});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.