[英]How to update state multiple times on same event using React useState hook?
I was wondering if it's possible to update state multiple times in a single event.我想知道是否可以在一个事件中多次更新 state。 Say I have a form where multiple
inputs
may need to be used to update a single state based on some logic like the below example:假设我有一个表单,其中可能需要使用多个
inputs
来更新单个 state 基于以下示例的一些逻辑:
State defined in parent component: State 在父组件中定义:
import React, { useState } from "react";
function ParentComponent() {
const [state, setState] = useState([]);
return (
<ChildComponent state={state} setState={setState} />
)};
export default ParentComponent;
State updated in child component: State 在子组件中更新:
import React, { useState } from "react";
function ChildComponent(props) {
const onSubmit = data => {
if(someLogicHere) {
props.setState(_ => [...props.state, data]);
}
if(someOtherLogicHere) {
props.setState(_ => [...props.state, data]);
}
}
return (
//Form goes here
)};
export default ChildComponent;
When using this method, only the output of the first if
statement is returned onSubmit
and added to the state object.使用此方法时,仅返回第一个
if
语句的 output onSubmit
并添加到 state object。 Is there a way to have the output from all possible if
statements be added? if
添加语句,有没有办法让 output 尽可能多地添加?
I would build the array first then update the state once, something like that:我会先构建数组,然后更新 state 一次,如下所示:
const onSubmit = data => {
let result = [...props.state];
if(someLogicHere) {
result.push(data);
}
if(someOtherLogicHere) {
result.push(data);
}
props.setState(result);
}
You can use the callback form of setState
for that:您可以为此使用
setState
的回调形式:
function ChildComponent(props) {
const onSubmit = data => {
if(someLogicHere) {
props.setState(state => [...state, data]);
// −−−−−−−−−−−−−−−−−−−−−^^^^^−−−−−−−−^^^^^
}
if(someOtherLogicHere) {
props.setState(state => [...state, data]);
// −−−−−−−−−−−−−−−−−−−−−^^^^^−−−−−−−−^^^^^
}
}
return (
//Form goes here
)};
That ensure that overlapping calls don't result in lost data.这确保重叠调用不会导致数据丢失。
Don't use multiple setState()
in all if conditions instead create a combined update object and then merge into state如果条件不使用多个
setState()
而是创建组合更新 object 然后合并到 state
eg例如
const onSubmit = data => {
const data = {};
if(someLogicHere) {
data['a'] = 1;
}
if(someOtherLogicHere) {
data['b'] = 2;
}
if(anotherLogic) {
data['b'] = data['b'] + 10;
}
props.setState(_ => [...props.state, data]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.