[英]Why is my state replacing my posts when I add a new one using React hooks and React context
我正在創建一個新應用程序,我希望能夠將更新發布給我的朋友。 一個微博網站。
我想學習如何使用 React 鈎子和 React 的上下文 API 來更新應用程序。 我創建了以下提供程序,它將 state 作為值...我希望能夠添加一個新帖子,然后更新該州的帖子,這樣我就不必再次獲取數據庫(使用 firestore)我真的想為自己節省一個對數據庫的調用......
Basically, when I call createNewPost within the state, I want to be able to update the current posts section of the state: state.posts
but when I update the state after the API call is successful, my entire posts array gets replaced for some reason . 不知道我可能做錯了什么......
import { createContext, useState } from 'react';
import { createDoc, getWhere } from '../utils/database/db';
export const PostDataContext = createContext();
const SetDataContextProvider = ({ children }) => {
const [state, setState] = useState({
posts: [],
timelinePosts: [],
createNewPost: async (collection, payload) => {
const doc = await createDoc(collection, payload)
payload.id = doc?.doc?.id;
updateStatePosts(payload);
return doc;
},
getPostsByUserId: async (userId) => {
const dataReceived = await getWhere('/posts', userId, 'userId')
setState({ ...state, posts: dataReceived })
}
});
const updateStatePosts = (payload) => {
console.log('why is state posts empty?!', state);
setState({ ...state, posts: [payload, ...state.posts] })
}
return <PostDataContext.Provider value={state}>
{children}
</PostDataContext.Provider>
}
export default SetDataContextProvider;
如果我不得不猜測,我會說您在 state 中使用的updateStatePosts
function 中有一個陳舊的初始空posts
state 外殼。 您可以使用功能 state 更新來訪問以前的 state 以進行更新。 功能 state 更新允許您從以前的 state 進行更新,而不是從 state 更新已排隊/包含在其中。
const SetDataContextProvider = ({ children }) => {
const [state, setState] = useState({
posts: [],
timelinePosts: [],
createNewPost: async (collection, payload) => {
const doc = await createDoc(collection, payload)
payload.id = doc?.doc?.id;
updateStatePosts(payload);
return doc;
},
getPostsByUserId: async (userId) => {
const dataReceived = await getWhere('/posts', userId, 'userId')
setState(prevState => ({
...prevState, // <-- preserve any previous state
posts: dataReceived
}))
}
});
const updateStatePosts = (payload) => {
setState(prevState => ({ // <-- previous state to this update
...prevState,
posts: [payload, ...prevState.posts],
}));
};
return <PostDataContext.Provider value={state}>
{children}
</PostDataContext.Provider>
}
這個 function 是錯誤的:
const updateStatePosts = (payload) => {
console.log('why is state posts empty?!', state);
setState({ ...state, posts: [payload, ...state.posts] })
}
您為 state 正確使用了擴展運算符,但直接替換了posts
。 您可能想要使用以下setState
:
setState({ ...state, posts: [...payload,...state.posts] })
盡管如此,您還應該重構您的state
。 函數不是狀態,所以將它們放在 state 之外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.