javascript - 如何在反应(钩子)中更新值而不是重新渲染完整的应用程序?
问题描述
在这里,我尝试使用 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?
解决方案
定义 Context 的值时,您需要定义值和回调函数来更改该值。我认为您应该阅读并遵循此反应文档 https://reactjs.org/docs/context.html#updating-context-from-a-nested-component
推荐阅读
- copy - 从 .jpeg 文件文件夹中的列表中复制 .cr2 文件
- javascript - 将 HTML 呈现为... HTML?在香草 JS
- pdf - 在 Drupal 8 中,更新或创建特定类型的节点时,我想将 pdf 版本保存到文件中
- android - 在图像上写文本 Xamarin android
- python-3.x - 当从不同的模块调用子例程时,程序尝试导入 paramiko 失败
- r - 如何在基于 debian 的发行版中切换 BLAS 版本以与 R 一起使用?
- dynamic - 如何从 Kivy 中经常更新的列表中创建动态标签列表
- post - 使用 XMLHttpRequest 并发布
- git - 尽管将文件添加到 .gitignore 中,但文件不会被忽略
- leaflet - Leaflet 仅渲染游戏地图 y 坐标为 0 的图块