简体   繁体   English

fetch 到 useEffect 钩子后,如何将响应信息保存在 Redux state 中?

[英]How to save the response info in the Redux state after fetch into useEffect hook?

I have the following case:我有以下情况:

 export default function Names() { const dispatch = useDispatch(); const [names, setNames] = useState([]); const stateNames = useSelector(state => state.names); const fetchNames = async () => { try { const response = await nameService.getNames(); dispatch(initNames(response.body)); setNames(response.body); } catch (error) { console.error('Fetch Names: ', error); } }; useEffect(() => { fetchNames(); }, []); return ( { names.map((name, index) => ( <Tab label={ budget.label} key={index}/> )) } ); }

When my component is rendered in the browser console I get a warning: "React Hook useEffect has a missing dependency: 'fetchBudgets'. Either include it or remove the dependency array react-hooks / exhaustive-deps".当我的组件在浏览器控制台中呈现时,我收到一条警告:“React Hook useEffect 缺少依赖项:‘fetchBudgets’。要么包含它,要么删除依赖项数组 react-hooks / exhaustive-deps”。 If I comment the line in which I write the names in Redux state, the warning does not appear.如果我在 Redux state 中注释我写名字的行,则不会出现警告。 I need the list of names in the state so that I can update the list when a new name is written to the list from the outside.我需要 state 中的名称列表,以便在从外部将新名称写入列表时更新列表。

export default function AddNameComponent() {
  const dispatch = useDispatch();
  const [label, setLabel] = useState('');
  const [description, setDescription] = useState('');

  const onLabelChange = (event) => { setLabel(event.target.value); };
  const onDescriptionChange = (event) => { setDescription(event.target.value); };

  const handleSubmit = async (event) => {
    try {
      event.preventDefault();
      const newName = {
        label: label
        description: description
      };
      const answer = await budgetService.postNewName(newName);
      dispatch(add(answer.body)); // Adding new Name in to Redux state.names
    } catch (error) {
      setErrorMessage(error.message);
      console.error('Create Name: ', error);
    }
  };

  return (
    <div>
      // Create name form
    </div>
  )
}

This is how everything works, but I don't understand why I have a warning.这就是一切的运作方式,但我不明白为什么我会收到警告。 I tried to add a flag to the array with dependencies of usеЕffect.我试图用 useEffect 的依赖项向数组添加一个标志。 I tried to pass the function 'fetchNames' through the parent component - in props and to add it as a dependency, but it is executed twice... Can you advise please!我试图通过父组件传递 function 'fetchNames' - 在 props 中并将其添加为依赖项,但它被执行了两次......请你指教!

It's just an eslint warning so you don't have to fix it.这只是一个 eslint 警告,因此您不必修复它。 But basically any variables which are used in the useEffect function are expected to be included in the dependency array.但基本上在useEffect function 中使用的任何变量都应该包含在依赖项数组中。 Otherwise, the effect will never be re-run even if the function fetchBudgets were to change.否则,即使 function fetchBudgets发生变化,效果也永远不会重新运行。

It is expecting your hook to look like它期待你的钩子看起来像

useEffect(() => {
    fetchBudgets();
}, [fetchBudgets]);

Where the effect will run once when the component is mounted and run again any time that the fetchBudgets function changes (which is probably never).效果将在组件安装时运行一次,并在fetchBudgets function 更改(可能永远不会)时再次运行。

If it's executing more than once, that means that fetchBudgets has changed and you should try to figure our where and why it has been redefined.如果它执行了不止一次,这意味着fetchBudgets已经改变,你应该试着弄清楚我们在哪里以及为什么它被重新定义了。 Maybe it needs to be memoized?也许它需要记忆?

Here are the docs on putting functions in the dependency array. Here are the docs on putting functions in the dependency array。

Thanks for your attention.感谢您的关注。 I tried many options and finally found one solution.我尝试了很多选择,最后找到了一个解决方案。

    useEffect(() => {
    async function fetchNames() {
      const response = await nameService.getNames();
      dispatch(init(response.body));
      setNames(response.body);
    }

    fetchNames();
  }, [dispatch, props]);

I put 'props' in an array of dependencies for one useEffect execution.我将 'props' 放在一组依赖项中以执行一次 useEffect。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM