简体   繁体   English

React Context - 设置状态然后直接引用它?

[英]React Context - Set state then reference it straight after?

I am working with a list of items and I want to set a selected item id, then fetch the selected item using the id.我正在处理一个项目列表,我想设置一个选定的项目 id,然后使用该 id 获取选定的项目。

I am updating the state of a context using reducers which works, but when referencing the property of the state, it doesn't see the updated value.我正在使用有效的减速器更新上下文的状态,但是在引用状态的属性时,它看不到更新的值。

Component.js组件.js

  useEffect(() => {
    setSelectedId(5);
    getSelectedItem();
  }, []);

Context.js上下文.js

  const initialState = {
    selectedId: 0,
  };

  const [state, dispatch] = useReducer(ItemReducer, initialState);

  const setSelectedId = id => dispatch({ type: SET_SELECTED_ID, payload: id });

  // HERE IT THINKS 'state.selectedId' IS 0
  const getSelectedItem = async () => {
     const selectedItem = await fetch(url + state.selectedId);
  };

Chrome 开发工具

The Chrome dev tools show the selected id property is updated to 5, but the getSelectedItem function sees 'selectedId' as 0 not 5. Chrome 开发工具显示 selected id 属性已更新为 5,但 getSelectedItem 函数将“selectedId”视为 0 而不是 5。

This could be a simple issue and any help would be appreciated.这可能是一个简单的问题,任何帮助将不胜感激。

Thanks谢谢

You will need to resolve the promise that would be returned.您将需要解决将返回的承诺。 Something like:就像是:

useEffect(() => {
    setSelected(5).then(getSelectedItem());

  }, []);

You could move getSelectedItem();你可以移动getSelectedItem(); into its own useEffect that's dependent on the selectedItemId, that way it will only perform getSelectedItem once the value of selectedId is set.进入它自己的依赖于 selectedItemId 的 useEffect,这样它只会在设置 selectedId 的值后执行 getSelectedItem。

useEffect(() => { 
   if(selectedId) getSelectedItem();
}, [selectedId]);

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

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