在React中的多个上下文提供者之间传递数据

时间:2019-11-15 10:45:32

标签: reactjs react-context

我有几个上下文提供程序(UserContextProvider和PostContextProvider)。我需要在PostContextProvider内部使用UserContextProvider中的值(用户),该怎么做?

class CustomUserManager(BaseUserManager):
    use_in_migrations = True

    ...
//user context

export const UserContext = React.createContext({ user: null});
export const UserContextProvider = (props) => {
 const [user, setUser] = useState(null);

 const getUser = async () => {
    ...fetch user data form the api
    setUser(response.data);
 }

 return <UserContext.Provider value={user}>{props.children}</UserContext.Provider>;
}
//post context

export const PostContext = React.createContext({ post: null});
export const PostContextProvider = (props) => {
 const [post, setPost] = useState(null);

 const getUser = async () => {
    ...fetch post data form the api
    setPost(response.data);
 }

 return <PostContext.Provider value={post}>{props.children}</PostContext.Provider>;
}

0 个答案:

没有答案