【发布时间】: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