[英]React, why state doesn't change?
这是一个关于派生 state 的简单示例。
这里是沙箱 url: https://codesandbox.io/s/review-react-derived-state-2-forked-v9ucpr?file=/src/App.js
当我单击按钮时,我期望值从 0 变为 10。 但是,它也不渲染,它的流程很奇怪。 我点击按钮几次,它不会重新渲染,即使改变了value
。
这是代码:
import { useState, useEffect } from "react";
export default function App() {
console.log("App is called!");
const [value, setValue] = useState(() => {
console.log("App useState is alloc");
return 0;
});
console.log("App is END");
return (
<div>
<NumberInput value={value} onChange={setValue} />
<button onClick={() => setValue(10)}>change to ten</button>
</div>
);
}
function NumberInput({ value, onChange }) {
console.log(" NumberInput is called!");
const [inputValue, setInputValue] = useState(value);
useEffect(() => {
const numberValue = Number(inputValue);
onChange(numberValue);
}, [inputValue, onChange]);
console.log(" NumberInput is END");
return (
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
);
}
您的
const [inputValue, setInputValue] = useState(value);
将 prop value
“分叉”到本地 state,因此初始挂载后对value
的更改不会反映在inputValue
中。 你需要
useEffect(() => setInputValue(value), [value]);
在子组件中将value
属性的任何更改也镜像到inputValue
。
当value
更改时,您不会更新NumberInput
的内部 state。
这将是解决问题的代码:
import { useState, useEffect } from "react";
export default function App() {
const [value, setValue] = useState(0);
return (
<div>
<NumberInput value={value} onChange={setValue} />
<button onClick={() => setValue(10)}>change to ten</button>
</div>
);
}
function NumberInput({ value, onChange }) {
const [inputValue, setInputValue] = useState(value);
useEffect(() => {
onChange(+inputValue);
}, [inputValue, onChange]);
// We add a use effect that will get trigger when the parent
// value changes
// However, this implies that the NumberInput will always render
// because of the previous useEffect, which also updates the
// value's value
useEffect(() => {
setInputValue(`${value}`);
}, [value]);
return (
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
);
}
useState 只会在初始化子组件时捕获您的值。 尝试:
<input value={value}
// instead of
<input value={inputValue}
我希望那是你想要的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.