开发者问题收集

如何在 React 中使用 context api 向 rest api 添加数据?

2021-07-11
339

我想通过操作将数据添加到 restfull api。 但我收到此错误。

export const GlobalContext = createContext();
const GlobalProvider = ({ children }) => {
const [userData, setUserData] = useState([]);
const [meetings, setMeetings] = useState([]);
useEffect(() => {
    fetch('http://localhost:4000/users')
        .then(res => res.json())
        .then(data => {
            setUserData(data);
            dispatch({
                type: 'CREATE_MEETING',
                paylaod: data
            })
        });
    fetch('http://localhost:4000/meeting')
        .then(res => res.json())
        .then(data => setMeetings(data));
}, []);
const [state, dispatch] = useReducer(AppReducer, meetings);
//Actions
const updateProfile = (id) => {
    dispatch({
        type: 'UPDATE_PROFILE',
        payload: id
    })
};
const createMeeting = (meeting) => {
    dispatch({
        type: 'CREATE_MEETING',
        paylaod: meeting
    })
};
return (
    <GlobalContext.Provider value={{
        meeting: meetings, userData, createMeeting
    }}>
        <MuiPickersUtilsProvider utils={DateFnsUtils}>
            {children}
        </MuiPickersUtilsProvider>
    </GlobalContext.Provider>
)

} export default GlobalProvider

在此处输入图片描述 reducer const Reducer = (state, action) => { switch (action.type) { case 'CREATE_MEETING': return { meeting: [action.payload, ...state.meetings]

    default:
        return state;
}

} export default Reducer;

如何使用 fetch 将数据添加到 api?

 case 'CREATE_MEETING':
        console.log(state)
        return [...state,
        fetch('http://localhost:4000/meeting', {
            method: 'POST',
            headers: { "Content-type": "Application/json" },
            body: JSON.stringify(state)
        })
        ]  

你能帮我吗?

1个回答

在数组与对象中扩展未定义 中所述,在尝试扩展 undefined 时会收到 TypeError。

将您的 setMettings 包装在条件中:

data => {
    if (data) {
        setMeetings(data)
    }
}

或者在您的 Reducer 中为 state.mettings 提供默认值:

const reducer = (state, action) => { 
    switch (action.type) {
        case 'CREATE_MEETING':
            return { meeting: [action.payload, ...(state.meetings || [])] }
    }
}
j-petty
2021-07-11