【问题标题】:React Context Provider doesn't correct see state from useStateReact Context Provider 无法正确查看来自 useState 的状态
【发布时间】:2020-10-12 21:37:44
【问题描述】:

我的 react 应用程序有一个如下所示的上下文提供程序。我将“addNewLocation”功能公开给消费者以便能够调用。我希望这个函数只在 state.tripList 中不存在的情况下添加一个新位置。该函数可以很好地更新状态,除了检查 state.tripList 中的内容的行。我添加了 console.log,它每次都将数组视为空,即使 React 开发工具告诉我不是这样。

如果您有任何想法,请提前致谢。我只是希望能够看到状态。


export const TripContext = createContext();

// This context provider is passed to any component requiring the context
export const TripProvider = ({ children }) => {
  // Function to add a new location to the state above
  const addNewLocation = (location) => {
    alert(JSON.stringify(state.tripList)); // debugging, tripList always is seen as empty
    /* IF THERES ALREADY THE LOCATION IN STATE, I DON'T WANT TO ADD IT */
    if (!state.tripList.includes(location)) { // This line never returns false, it always sees tripList as empty
      setState(prevState => ({
        ...prevState,
        tripList: [...prevState.tripList, ...[location]]
      }));
    }
  }

  // User passes a location, remove it
  const removeLocation = (location) => {

  }

  const initState = {
    tripList: [],
    addNewLocation: addNewLocation,
  }

  // create state (with initial value initState) and a function to update it
  const [state, setState] = useState(initState)

  return (
    <TripContext.Provider
      value={state}
    >
      {children}
    </TripContext.Provider>
  );
};

【问题讨论】:

  • 一切似乎都很好,尝试使用最小的可重现示例进行编辑。此外,执行...[location] 与仅使用location 相同

标签: reactjs react-hooks react-context


【解决方案1】:

您已将初始 tripList 状态 ([]) 包含在 addNewLocation 中,然后加倍将回调也包含在状态中。这意味着您的状态已过时;总是从相同的“先前”状态更新。

上下文的值应该是tripList 状态并且只是对非封闭回调的引用。不要将回调存储在本地组件状态中。

const TripProvider = ({ children }) => {
  // Function to add a new location to the state above
  const addNewLocation = (location) => {
    console.log(JSON.stringify(tripList)); // debugging, tripList always is seen as empty
    if (!tripList.includes(location)) {
      setTripList((tripList) => [...tripList, location]);
    }
  };

  // User passes a location, remove it
  const removeLocation = (location) => {};

  // create state (with initial value initState) and a function to update it
  const [tripList, setTripList] = useState([]);

  return (
    <TripContext.Provider
      value={{
        tripList, // <-- state value
        addNewLocation // <-- update callback
      }}
    >
      {children}
    </TripContext.Provider>
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2022-11-09
    • 1970-01-01
    • 2020-07-08
    • 2019-10-17
    • 2021-11-13
    • 2023-03-07
    • 2022-10-01
    相关资源
    最近更新 更多