useEffect 数据 React 中的逗号预期错误
Comma expected error in useEffect data React
我从数据中得到“,”(逗号)预期错误:{...sample.data, res.data} 错误指向点“.”共 res.data
useEffect(()=>{
axios.get('http://localhost:1234/hello').then((res)=>{
{console.log(res.data)}
setSample({
...sample,
data: {...sample.data, res.data}
})
{console.log(sample)}
})
}, [])
您可以使用方括号
useEffect(()=>{
axios.get('http://localhost:1234/hello').then((res)=>{
console.log(res.data);
setSample({
...sample,
data: {...sample["data"], ...res["data"]}
});
console.log(sample) // this not working because setSample is Promise function
})
}, [])
你也必须传播 res.data
.. 考虑下面的例子
const [sample, setSample] = useState({data: {value: 'initial'}});
useEffect(() => {
const res = {
data: {
another_value: "from api"
}
};
setSample({
...sample,
data: { ...sample.data, ...res.data }
});
}, []);
sample
的初始状态有 属性 value
,值为 initial。在 useEffect
中,我们向示例对象添加了一个值。这将导致输出,
{value: "initial", another_value: "from api"}
如果您将 console.log(sample)
记录在 setSample
下方,则 console.log(sample)
也不会显示更新后的值。你可能想添加一个 useEffect
和 sample
作为依赖,它会监听样本的变化。
useEffect(() => {
console.log(sample);
}, [sample]);
我从数据中得到“,”(逗号)预期错误:{...sample.data, res.data} 错误指向点“.”共 res.data
useEffect(()=>{
axios.get('http://localhost:1234/hello').then((res)=>{
{console.log(res.data)}
setSample({
...sample,
data: {...sample.data, res.data}
})
{console.log(sample)}
})
}, [])
您可以使用方括号
useEffect(()=>{
axios.get('http://localhost:1234/hello').then((res)=>{
console.log(res.data);
setSample({
...sample,
data: {...sample["data"], ...res["data"]}
});
console.log(sample) // this not working because setSample is Promise function
})
}, [])
你也必须传播 res.data
.. 考虑下面的例子
const [sample, setSample] = useState({data: {value: 'initial'}});
useEffect(() => {
const res = {
data: {
another_value: "from api"
}
};
setSample({
...sample,
data: { ...sample.data, ...res.data }
});
}, []);
sample
的初始状态有 属性 value
,值为 initial。在 useEffect
中,我们向示例对象添加了一个值。这将导致输出,
{value: "initial", another_value: "from api"}
如果您将 console.log(sample)
记录在 setSample
下方,则 console.log(sample)
也不会显示更新后的值。你可能想添加一个 useEffect
和 sample
作为依赖,它会监听样本的变化。
useEffect(() => {
console.log(sample);
}, [sample]);