首先,您在添加汽车时在哪里更新状态。
function handleSubmit(e) {
e.preventDefault();
let car = e.target.elements["car"].value;
setCars((prevState) => {
return [...prevState, car];
});
}
我从您的仓库复制的上述代码,仅将新添加的汽车更新为本地状态。这就是它在上下文中不可用的原因。您已经创建了一个全局上下文,但没有使用它。
你要做的是,
在您的 carInput 类中访问上下文
const [initialState, dispatch] = useCarContext();
function handleSubmit(e) {
e.preventDefault();
let car = e.target.elements["car"].value;
// Instead of updating to local state,
//upadate your global context using dispatch
// in dispatch pass actionType and the value
dispatch({ type: 'updateNewCar', value: car });
}
还附上示例上下文实现(您可以根据自己的用例进行更改)
import React, { createContext, useContext, useReducer } from "react";
export const initCarContext = () => {
return {
initialState: {
cars: []
},
reducer: function (state, { type, value }) {
switch (type) {
case 'updateNewCar':
state.cars.push(value)
return { ...state };
default:
return state;
}
}
};
};
export const StateContext = createContext();
export const CarStateProvider = ({ reducer, initialState, children }) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
export const useCarContext = () => useContext(StateContext);
https://kentcdodds.com/blog/how-to-use-react-context-effectively/