在这里,我尝试使用 Context-API 将标头组件的值更新为搜索组件。在我的情况下,我在标题组件中有一个下拉列表,我想将下拉值传递给搜索页面而不重新呈现搜索组件。这是我的示例代码
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?
答案 0 :(得分:0)
当定义 Context 的值时,您需要定义值和回调函数来更改该值。我认为你应该阅读并遵循这个反应文档 https://reactjs.org/docs/context.html#updating-context-from-a-nested-component