[英]React 16.13: useState wait for state to update before render
I have an array of strings, and it's count in state:我有一个字符串数组,它在状态中计数:
const [count, setCount] = useState(0);
const [strings, setStrings] = useState([""]);
So in the beginning I always have an element in the state.所以一开始我总是在状态中有一个元素。 On a button click I'm adding to the count and the list:
单击按钮,我将添加到计数和列表中:
function onClickAdd() {
setStrings(prev => [...prev, ""]);
setCount(count + 1);
}
I'm rendering multiple text fields based on this count, and the value of those text fields is set from the array index (range is a custom function, returns array of values from start -> end):我正在根据此计数呈现多个文本字段,并且这些文本字段的值是根据数组索引设置的(范围是一个自定义函数,从开始 -> 结束返回值数组):
function makeInputs(count, onRemove) {
return range(1, count).map(id => {
return (
<TextInput type="url" validate onChange={e => onChange(e, id)} value={strings[id]}
icon={<Button style={{backgroundColor: "red"}} onClick={() => onRemove(id)}><Icon>remove</Icon></Button>} />
);
});
}
But whenever I click the add button, new field is rendered and the value of new fields is set to undefined (strings array is not updated yet), and I get a warning:但是每当我单击添加按钮时,都会呈现新字段并且新字段的值设置为未定义(字符串数组尚未更新),并且我收到警告:
index.js:1 Warning: A component is changing an uncontrolled input of type url to be controlled.
index.js:1 警告:组件正在更改要控制的 url 类型的不受控制的输入。 Input elements should not switch from uncontrolled to controlled (or vice versa).
输入元素不应从不受控制切换到受控制(反之亦然)。 Decide between using a controlled or uncontrolled input element for the lifetime of the component
决定在组件的生命周期内使用受控或不受控制的输入元素
How can I delay the render until list is resized?如何在调整列表大小之前延迟渲染? I've tried moving
setCount()
to useEffect()
but doing that doesn't make the new fields show up at all.我试过将
setCount()
移动到useEffect()
但这样做根本不会显示新字段。
https://codesandbox.io/s/aged-dew-eud84?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/s/aged-dew-eud84?fontsize=14&hidenavigation=1&theme=dark
Try this尝试这个
function Form() {
const [values, setValues] = useState([]);
return (
<div>
<button onClick={() => setValues([...values, ""])}>Add</button>
{values.map((value, idx) =>
<div key={String(idx)}>
<input
type="text"
value={value}
onChange={(e) => {
values[idx] = e.target.value;
setValues([...values]);
}}
/>
</div>
)}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.