【问题标题】:after axios get my setState hooks doesn't run在 axios 得到我的 setState 钩子后没有运行
【发布时间】:2021-11-26 17:13:06
【问题描述】:

我有很多这样的功能,使用相同的方法,它们都运行良好。 但是这个让我发疯了。

我的代码是:

    const [match,setMatch] = useState(null);

      axios.get(path)
        .then((res) => {
            status = res.data; 
            setMatch(res.data)});

    const test = match;

如果我调试程序并在setMatch(status) 处中断,res.data 的内容是正确的: res.data 是一个数组,每个元素都包含值和对象的混合,如下面的屏幕截图所示。

但是当我执行setMatch(status) 时,结果是match 状态变量没有改变:它仍然是第一次设置的null

有人可以提供一些建议吗?

【问题讨论】:

  • match设置后的值在哪里查看?
  • 你的意思是在调试期间? setMatch 是异步的,所以不会被立即调用
  • 我更改了代码,在断点处添加了一个新行。在const test = match; 中匹配为空。但是要填充它的数据存在于调试器中。在代码中,我在调试器中检查了它。
  • 确保在 useEffect 中运行 ajax 调用,否则每次渲染都会发生。
  • 它是否在带有数据依赖关系的 useEffect 中?

标签: reactjs axios react-hooks


【解决方案1】:

根据您的问题,我不知道什么可能会影响您的代码运行。但这是处理异步请求时的常见模式。 预计它应该在绘制后立即在 useEffect 挂钩中执行

const Component = () => {
    const [match,setMatch] = useState([]);
    
    useEffect(() => {
       axios.get(path)
          .then((res) => {
            status = res.data; 
            setMatch([match, ...res.data])})
          .catch((err) => handleError(err));
    }, [path]) // assuming that the path changes otherwise  if you are running this once, leave the array empty
     
return (<div> {(match.length > 0)? 'Loading': {renderYourLogicHere} </div>)
}

【讨论】:

  • .then 内有status = res.data 已被弃用。为什么不只是.then((res) =&gt; {setData(res.data)});
猜你喜欢
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 2019-11-26
  • 2019-01-12
  • 2021-08-03
  • 2023-03-07
相关资源
最近更新 更多