Sto*_*ace 1 javascript reactjs
我想知道最好的方法是key/value为statein a定义多于一对Functional Component。
在一类我会initialitheState喜欢
this.state = {
first: 'foo',
second: 'bar'
};
Run Code Online (Sandbox Code Playgroud)
更新State我的电话
this.setState({
first: 'foobar'
second: 'barfoo'
});
Run Code Online (Sandbox Code Playgroud)
现在React Hooks我State像这样初始化。
const [first setfirst] = useState('foo');
const [second, setSecond] = useState('bar');
Run Code Online (Sandbox Code Playgroud)
更新State我的电话
setFirst = 'foobar';
setSecond = 'barfoo';
Run Code Online (Sandbox Code Playgroud)
但是,恕我直言,这并不理想。我不得不重写const [x, setX] = useState(...);每次我想要一个新的添加key/value对到State object。样板。我还必须始终牢记 的“二传手”名称x,即setX. 如果State object增长,那将变得混乱。
如果我可以简单地打电话会更好
setState(first: 'foobar', second: 'barfoo');
Run Code Online (Sandbox Code Playgroud)
但我不确定如何State object正确初始化/最好的方法是什么。
您可以使用 useState 设置整个对象,如下所示 -
const [stateObj, setStateObj] = useState({first:'foobar', second:'barfoo'});
Run Code Online (Sandbox Code Playgroud)
然后更新状态 -
setStateObj({first:'foobarnew', second:'barfoonew'})
Run Code Online (Sandbox Code Playgroud)
使用对象作为初始值
您可以使用 ajavascript object作为您的值。通过这种方式,您可以将更多变量放在对象中的一个位置。所以你的代码如下所示:
const [example, setExample] = useState({first:'foobar', second:barfoo''});
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样更新它:
setExample({...example,first:'new foobar'})
setExample({...example,second:'new foobar second'})
Run Code Online (Sandbox Code Playgroud)
这种类型setting是解构您以前的值,并用旧值替换您的新值。
使用这个对象,你只需要你的新添加property到的初始化example以及您需要设置的地方。
作为一个复杂的例子,您可以访问此链接:
注意(更新变量)
如果您只是使用更新它{first:'new foobar'}而不包含second在您的属性中,您可能会失去 second 的旧值。所以使用...example来获得 的旧值second。