我有一些默认的彩色十六进制代码,在获取请求后,我会对其进行更新。我注意到请求后状态已更改,但应用未重新呈现。例如,如果我来回切换选项卡,我将看到新状态。
因此,当应用加载时,即使它已更改,我也会看到第一个状态。如果我重新渲染,我会看到新的值。
我提供了一些代码以及带有虚拟数据的codeandbox的链接。
const [colorsList, setColorsList] = useState({
color1: "#ff0000",
color2: "#ffffff"
});
useEffect(() => {
let isSubscribed = true;
async function fetchData() {
await fetch(`https://...`, {
headers: {
"Content-Type": "application/json;charset=UTF-8",
Authorization: `Bearer mytoken`
}
})
.then(response => {
return response.json();
})
.then(data => {
if (isSubscribed) {
const fetchedJson = data;
// the json has the same structure as my initial state
setColorsList(fetchedJson);
// here i see that the state have changed
console.log("colorsList: ", colorslist);
}
});
}
fetchData();
return () => {
isSubscribed = false;
};
}, []);
return (
<form id="colors-form" onSubmit={handleSubmit}>
<div className="colors-container">
<div className="colors-1">
// these normally are material textfields. I used div for
// the sandbox
<div color="color1" defaultcolor={colorsList.color1}>
{colorsList.color1}
</div>
<div color="color2" defaultcolor={colorsList.color2}>
{colorsList.color2}
</div>
</div>
</div>
</form>
)
Codesandbox示例链接:here