javascript 如何设置多个状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52235160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to setState multiple states?
提问by Saif Khan
I have Multiple properties and everyone has it own state. How do I state multiple states at the same time ? There is this one way
我有多个属性,每个人都有自己的状态。我如何同时声明多个状态?有这种方法
ChangeName(event){
const details = this.state.details;
details.first_name = event.target.value;
this.setState({details: details});
}
and bind it this way
并以这种方式绑定
this.ChangeName = this.ChangeName.bind(this);
So I have a form with these different properties
所以我有一个具有这些不同属性的表格
this.state={
details :{first_name: "",
last_name:"",
address:"",
company:"",
number:"",
dob:""
}
So do I have create function for every property and bind everyone separately the way I mentioned above ? Or is there any other way that I am not aware of as I am new to react.
那么我是否为每个属性创建了函数并按照我上面提到的方式分别绑定每个人?或者有没有其他我不知道的方式,因为我是新手。
Thank you !
谢谢 !
回答by sventschui
To answer your question about updating multiple properties of the state: You can absolutely do this. setStateaccepts an object with updates. Thus setState({ foo: '', bar: '' })will update the fooand barproperties.
要回答有关更新状态的多个属性的问题:您绝对可以这样做。setState接受带有更新的对象。因此setState({ foo: '', bar: '' })将更新foo和bar属性。
To answer what I think you meant:
回答我认为你的意思:
When working with input fields the way to go is to create an event handler function for each field.
处理输入字段时,要走的路是为每个字段创建一个事件处理函数。
See the two examples of how to properly handle input fields with nested state or with top level state. I'd recommend to keep the fields top-level in the state as otherwise you'll have to deal with
请参阅有关如何正确处理具有嵌套状态或顶级状态的输入字段的两个示例。我建议保持该州的顶级字段,否则您将不得不处理
- the asynchroneous nature of setState
- deep object cloning in order to not mutate objects within the state
https://codepen.io/sventschui/pen/yxPrjP
https://codepen.io/sventschui/pen/yxPrjP
class AppWithDetails extends React.Component {
constructor(props) {
super(props)
this.onFirstNameChange = this.onFirstNameChange.bind(this);
this.onLastNameChange = this.onLastNameChange.bind(this);
this.state = {
details: {?first_name: '', last_name: '' }
}
}
onFirstNameChange(event) {
// store value because of react synthetic events
const value = event.target.value;
// use callback function in setState because of asynchronous nature of setState
this.setState(function(state) {
return {
details: Object.assign({},
state.details, {
first_name: value
})
}
})
}
onLastNameChange(event) {
// store value because of react synthetic events
const value = event.target.value;
// use callback function in setState because of asynchronous nature of setState
this.setState(function(state) {
return {
details: Object.assign({},
state.details, {
last_name: value
})
}
})
}
render() {
return (
<div>
State:
<pre>{JSON.stringify(this.state)}</pre>
<input type="text" onChange={this.onFirstNameChange} value={this.state.details.first_name} />
<input type="text" onChange={this.onLastNameChange} value={this.state.details.last_name} />
</div>
)
}
}
class AppWithoutDetails extends React.Component {
constructor(props) {
super(props)
this.onFirstNameChange = this.onFirstNameChange.bind(this);
this.onLastNameChange = this.onLastNameChange.bind(this);
this.state = {
first_name: '',
last_name: '',
}
}
onFirstNameChange(event) {
this.setState({ first_name: event.target.value })
}
onLastNameChange(event) {
this.setState({ last_name: event.target.value })
}
render() {
return (
<div>
State:
<pre>{JSON.stringify(this.state)}</pre>
<input type="text" onChange={this.onFirstNameChange} value={this.state.first_name} />
<input type="text" onChange={this.onLastNameChange} value={this.state.last_name} />
</div>
)
}
}
document.addEventListener("DOMContentLoaded", function(event) {
ReactDOM.render(<AppWithoutDetails />, document.getElementById('withoutdetails'));
ReactDOM.render(<AppWithDetails />, document.getElementById('withdetails'));
});
回答by Jonas Wilms
You could use a curried function and use bracket notation to set different props of the details:
您可以使用柯里化函数并使用括号表示法来设置细节的不同道具:
changeDetail(name) {
return event => {
this.setState(({ details }) => ({
details: { ...details, [name]: event.target.value }
}));
};
}
Then you can use it like this in the render()ed elements:
然后你可以像这样在render()ed 元素中使用它:
<input
onChange={this.changeDetail("lastName")}
value={this.state.details.lastName}
/>
<input
onChange={this.changeDetail("address")}
value={this.state.details.address}
/>
回答by hosein khan beigi
ChangeName(event){
this.setState({
details:{ first_name: 'Hyman', last_name:'high'}
});
}
render(){
const {details} = this.state
console.log(details.first_name)
}

