【问题标题】:Comma expected error in useEffect data ReactuseEffect 数据 React 中的逗号预期错误
【发布时间】:2021-11-04 20:39:44
【问题描述】:

我从数据中得到“,”(逗号)预期错误:{...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)}
     })
  }, [])

【问题讨论】:

    标签: react-native use-effect


    【解决方案1】:

    你可以使用方括号

    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"] 中收到 "," 和 ":" 预期错误
    • @Vista 哦.. 我错过了传播我更新了答案
    【解决方案2】:

    你也必须传播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,其值 = 初始值。在useEffect 中,我们向示例对象添加了一个值。这将产生一个输出,

    {value: "initial", another_value: "from api"}
    

    如果您将其记录在setSample 下方,console.log(sample) 也不会显示更新后的值。您可能想添加一个 useEffectsample 作为依赖项,它会监听样本中的变化。

      useEffect(() => {
        console.log(sample);
      }, [sample]);
    

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 2022-08-09
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2021-12-17
      相关资源
      最近更新 更多