React Context Provider无法正确查看useState的状态

时间:2020-10-12 21:37:44

标签: reactjs react-hooks react-context

我有一个下面的上下文提供程序,用于我的react应用程序。我将'addNewLocation'函数暴露给使用者以便能够调用。我希望此功能仅在state.tripList中尚不存在时添加一个新位置。该功能可以很好地更新状态,除了检查state.tripList中内容的行之外。我添加了console.log,即使每次React Dev工具告诉我时,它每次都将数组视为空。

如果有什么想法,请先谢谢。我只希望能够看到状态。


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>
  );
};

1 个答案:

答案 0 :(得分: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> ); }; 状态,并且 just 是对未封闭的回调的引用。不要将回调存储在本地组件状态。

error_log

Edit react-context-provider-doesnt-correct-see-state-from-usestate