我正在尝试使用上下文API以提供全局状态。为此,我创建了一个上下文文件,为我的应用程序提供基本状态。以下是我的上下文文件。问题是我从LeadForm组件中的上下文提供程序获得了正确的状态,但是在放置在LeadForm组件内部的分页中,从上下文提供程序获得的状态是错误的
export const LeadContext = createContext()
export const LeadProvider = props => {
const [postsPerPage] = useState(5);
const [totalPosts] = useState(20);
return (
<LeadContext.Provider value={[
postsPerPage,
totalPosts,
]}>
{props.children}
</LeadContext.Provider>
)
}
这是我的App组件
const App = () => {
return (
<LeadProvider>
<GlobalStyle />
<Router>
<Grid>
<Header />
<Switch>
<Route path="/Leads" component={LeadForm}></Route>
<Route path="/Opportunities" component={Opportunities}></Route>
</Switch>
<Navbar />
</Grid>
</Router>
</LeadProvider>
);
};
这是我的LeadForm组件,这里postsPerPage和totalPosts具有正确的值
const LeadForm = () => {
const [postsPerPage, totalPosts] = useContext(LeadContext)
// console.log(postsPerPage) => 5
// console.log(totalPosts) => 20
}
return (
<Wrapper>
<div className="container mt-5">
<Form onSubmit={handleOnSubmit}>
{/* ... */}
<button>Create Lead</button>
</Form>
<LeadItem />
</div>
<Pagination />
</Wrapper>
);
};
export default LeadForm;
但是,在放置在LeadForm组件内部的分页组件内部,上下文状态是错误的。为什么呢?
const Pagination = () => {
const [postsPerPage, totalPosts, paginate] = useContext(LeadContext);
// console.log(postsPerPage) => [], [{ … }], (2)[{ … }, { … }], ....
// console.log(totalPosts) =>
// context State updates from the useState() and useReducer() Hooks don't
// support the " + 'second callback argument.To execute a side effect after ' + 'rendering,
// declare it in the component body with useEffect()
return (
// ....
);
};
export default Pagination;