在这里,我尝试使用Context-API将header组件的值更新为search组件。在我的例子中,我在header组件中有一个dropdown,我希望将dropdown值传递给搜索页面,而不重新呈现搜索组件。下面是我的示例代码
import React,{useContext,useState} from "react";
import { RepoContext } from "../../App";
const App = ()=>{
const [RepoUrn, setRepoUrn] = useState("");
const handleRepo = (value) => { // Callback from Header to update the dropdown value and I am sending this context so the state is updated and rendering mutliple times
return setRepoUrn(value);
};
}
const Search =()=>{
const context = useContext(RepoContext);
console.log(context);
React.useEffect(()=>{
console.log('context',context) -> Found here re rendering multiple times
},[context]);
}<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>
**APP.js**
<RepoContext.Provider value={RepoUrn}>
<div className="app">
<>
<Header
locale={locale}
repoValues={RepoValues}
setLocale={setLocale}
onSelectRepo={handleRepo}
/>
<Route path="/" component={Search} />
</>
</RepoContext.Provider>
**Header.js**
<Dropdown isOpen={repoOpen} toggle={(e) => toggle(e, "Repo")}>
<DropdownToggle
tag="span"
data-toggle="dropdown"
aria-expanded={repoOpen}
data-value={dataUrn}
id="test"
>
{TruncateMessage(RepoValue)}
<img src={downarrow} className="downarrow" />
</DropdownToggle>
<DropdownMenu
style={dropDownStyles}
id="scroll_styles"
onClick={(e) => changeDropdownValue(e, "Repo")}
>
{props.repoValues.length > 0
? props.repoValues.map((item, index) => {
return (
<div
key={index}
className="subMenu"
data-value={item.urn}
data-shows={item.name}
>
<h6>{item.name}</h6>
</div>
);
})
: ""}
</DropdownMenu>
</Dropdown>
How can I pass dropdown value from header to context and subscribe in search without search component re rendering even if I get the new value from header?
发布于 2021-03-15 17:09:24
在定义Context的值时,您需要定义值和回调函数来更改该值。我认为你应该阅读并遵循这个react文档https://reactjs.org/docs/context.html#updating-context-from-a-nested-component
https://stackoverflow.com/questions/66634261
复制相似问题