【问题标题】:Why .then() which is in useEffect is not updating my state为什么 useEffect 中的 .then() 没有更新我的状态
【发布时间】:2022-11-15 07:44:23
【问题描述】:

targetMovie 在涉及到 rednering 时为 null。我找不到任何解决方案。第一次遇到无法解决的问题。请帮忙!

async function getMovie(id) {
  try {
    const res = await axios.get(apiEndPoint + "/" + id);
    const movies = await res.data;
    return movies;
  } catch (err) {
    console.log(err);
  }
}

const MovieEdit = () => {
  const { id } = useParams();
  const [targetMovie, setTargetMovie] = useState(null);

  useEffect(() => {
    getMovie(id)
      .then((mov) => {
        setTargetMovie(mov);
        console.log(mov);
      })
      .catch((err) => console.log(err));
  }, []);

  console.log(targetMovie);
  if (targetMovie) return <AddMovie movie={targetMovie} />;
  return <Navigate to="/not-found" />;
};

【问题讨论】:

  • 目前尚不清楚问题出在哪里。你能否请edit你的问题来描述你期望看到的与你实际看到的。您的日志记录显示您的期望吗?
  • 我感觉很清楚。 OP 认为 &lt;AddMovie&gt; 正在以空 targetMovie 呈现。
  • @KonradLinkowski 我看不出它在这里是如何应用的
  • 啊,你正在使用来自 react-router 的&lt;Navigate&gt;。我认为您应该阅读该组件的文档 ~ reactrouter.com/en/main/components/navigate

标签: reactjs asynchronous react-router react-state


【解决方案1】:

您需要代表 3 个状态:

  1. 您目前正在等待 getMovie 完成
  2. getMovie 成功完成
  3. getMovie 完成并返回 null/undefined

    您当前使用相同的条件 (!targetMovie) 来表示 1. 和 3. 这就是您遇到问题的原因。

    尝试这个:

    const MovieEdit = () => {
      const { id } = useParams();
      const [isFetching, setIsFetching] = useState(true);
      const [targetMovie, setTargetMovie] = useState(null);
    
      useEffect(() => {
        getMovie(id)
          .then((mov) => {
            setIsFetching(false);
            setTargetMovie(mov);
            console.log(mov);
          })
          .catch((err) => {
            console.log(err));
            setIsFetching(false);
          }
      }, []);
    
      if (isFetching) return null;
    
      if (targetMovie) return <AddMovie movie={targetMovie} />;
    
      return <Navigate to="/not-found" />;
    };
    

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2020-07-31
  • 2017-01-25
  • 2021-08-04
  • 2020-04-14
  • 2021-07-19
  • 2021-02-12
相关资源
最近更新 更多