setState 不适用于 boolen 的 React Native

问题描述 投票:0回答:1

这是我的代码,我想更改 isCourse 的布尔值,但没有更改。调试时显示错误。我还检查了 if 值显示 true

 const [appTheme, setAppTheme] = useState(Appearance.getColorScheme());
 const [isCourse, setIsCourse] = useState(false);

 useEffect(() => {
   const handleDynamicLinks = dynamicLinks()
     .getInitialLink()
     .then(link => {
       console.log('here is your link', link.url);
       if (link && link.url === 'https://englishmuni.page.link/course') {
         setIsCourse(true);
         // console.log('--*****--', isCourse, link.url);
       }
     });

   const unsubscribe = dynamicLinks().onLink(handleDynamicLinks);
   Appearance.addChangeListener(scheme => {
     setAppTheme(scheme.colorScheme);
   });
   return () => unsubscribe();
 }, [isCourse]);
react-native setstate
1个回答
0
投票

您应该小心

useEffect
内部的逻辑,以避免无限循环或任何意外的
isCourse
副作用,因为您正在其中设置其值 (
setIsCourse
)。

您可以调用两个

useEffect
,其中第一个没有依赖数组来初始化
isCourse
,第二个
useEffect
来观察
isCourse

的更改
useEffect(() => {
  //You can create an async function here and put the logic inside
  const handleDynamicLinks = async () => {
    try {
      const link = await dynamicLinks().getInitialLink();
      console.log('here is your link', link.url);
      if (link && link.url === 'https://englishmuni.page.link/course') {
        setIsCourse(true);
      }
    }
    catch (error) {
      //TODO when exception occurs
    }
  };

  //Call the function
  handleDynamicLinks();

  const unsubscribe = dynamicLinks().onLink(handleDynamicLinks);
  const themeListener = Appearance.addChangeListener(scheme => {
    setAppTheme(scheme.colorScheme);
  });

  return () => {
    unsubscribe();
    themeListener.remove();  // Assuming the listener has a remove() method. If not, adjust accordingly.
  };
}, []); //<-- As stated before, we setup the method when the component is mounted for the first time

现在进入第二个

useEffect
,我们实际上观察到
isCourse
的变化。

useEffect(() => {
  if (isCourse) {
    //Work with the logic here.
  }
}, [isCourse]); //<-- And here, we observe the changes to isCourse

通过将逻辑拆分为两个单独的

useEffect hooks
,您可以将用于设置
isCourse
的逻辑和用于响应其值变化的逻辑分开。这可以帮助避免潜在的陷阱,例如无限循环。

© www.soinside.com 2019 - 2024. All rights reserved.