异步/等待反应功能组件

时间:2020-03-19 08:46:13

标签: reactjs react-native async-await

我正在做类似以下的事情

https://stackoverflow.com/a/57847874/433570

 const LowerCard = (props) => {

   let { review_meta, step } = props
   const [component, setComponent] = useState('');
   const {state, editDispatch} = useContext(ReviewMetaEditCardDispatch);

   useEffect(() => {

     // https://stackoverflow.com/a/57847874/433570

     const setDynamicComponent = async () => {
       let DynamicComponent
       switch(state.step) {
       case 'title':
         DynamicComponent = await import('review/react/components/review-meta-edit-card/step/title')
         break
       }

       if (DynamicComponent) {
         setComponent(DynamicComponent.default)
       }
     }

     setDynamicComponent()
   }, []);


   if (!component) {
     return null
   }

   return (
     <View>
       <component/>
     </View>
   )
   }

上面的代码有效,但是当我在[]调用中删除useEffect时,会导致 index.js:1 Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function.

我猜这是在抱怨您不应该在setComponent内调用useEffect(这是一个钩子)。

我该如何克服?

2 个答案:

答案 0 :(得分:2)

您不应在useEffect内部直接使用异步功能。

这是我的解决方案,看它是否有效



const LowerCard = props => {
  let {review_meta, step} = props;
  const [component, setComponent] = useState('');
  const {state, editDispatch} = useContext(ReviewMetaEditCardDispatch);

  const setDynamicComponent = useCallback(async () => {
    let DynamicComponent;
    switch (state.step) {
      case 'title':
        DynamicComponent = await import('review/react/components/review-meta-edit-card/step/title');
        break;
    }

    if (DynamicComponent) {
      setComponent(DynamicComponent.default);
    }
  }, [state]);

  useEffect(() => {
    // https://stackoverflow.com/a/57847874/433570
    setDynamicComponent();
  }, [setDynamicComponent]);

  if (!component) {
    return null;
  }

  return (
    <View>
      <component />
    </View>
  );
};


答案 1 :(得分:1)

您的动态组件正在使用钩子,如果您调用importedComponent.default,React会在useEffect内使用钩子而引发抛出和错误错误。

相反,加载组件并在渲染时调用.default

我还向state.step依赖项数组中添加了useEffect,以确保在state.step发生变化时,就像在初始渲染状态时一样,重新运行效果。step不是{{ 1}}该组件将永远不会呈现,因为您提供了一个空的依赖项数组

title