简体   繁体   English

如何在Reactjs中具有多个getInitialState实例?

[英]How to have multiple instances of getInitialState in Reactjs?

This is my code in React. 这是我在React中的代码。 I have multiple instances of getInitialState for different functions. 我有多个getInitialState实例用于不同的功能。 However, I am finding that there may be a problem with getting them all to run this way. 但是,我发现让它们全部以这种方式运行可能存在问题。

getInitialState: function(){
if (localStorage.getItem('something'))
{return {signedin: true}}
else {return {signedin: false}}
},

getInitialState:function(){
return {error: true}
},

getInitialState:function(){
return {fliphouse: false}
},

To explain, the second instance of getInitialState , as is, does not work. 解释一下, getInitialState的第二个实例不起作用。 That is, unless, I flip the order of the second and third getInitialState . 也就是说,除非我翻转第二和第三getInitialState的顺序。 When I do that, the code runs as it should. 当我这样做时,代码将按预期运行。 But I get the feeling React is trying to tell me something. 但是我感觉到React正在设法告诉我一些事情。

Is this normally the way to organize React code within a component? 这通常是在组件内组织React代码的方法吗?

You can define them all in the same object: 您可以在同一对象中全部定义它们:

getInitialState() {
  return {
    signedIn: !!localStorage.getItem('something'),
    error: false,
    fliphouse: false
  };
}

You can change them individually anywhere in the component (except in the render() function), eg: 您可以在组件中的任何位置单独更改它们(render()函数除外),例如:

this.setState({ error: true }) // causes a new render

This is not the correct way to put the initial state of the component. 这不是放置组件初始状态的正确方法。 Initial state function is called only once when you component is about to mount; 初始状态函数仅在组件即将安装时被调用一次; over here you set the state of the component(what variables or object properties you need) and then update them accordingly using setState in other methods like componentDidMount etc.. 在这里,您可以设置组件的状态(所需的变量或对象属性),然后在诸如componentDidMount等其他方法中使用setState相应地更新它们。

So in your question I would say put all 3 variables signedIn, error and fliphouse in the state object and then update this object. 因此,在您的问题中,我想说的是将所有3个变量signedIn,error和fliphouse都放入状态对象,然后更新该对象。 So a single initialState function would do. 因此,只有一个initialState函数即可。

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

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