首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在react (Hooks)中更新值而不是重新渲染完整的应用程序?

如何在react (Hooks)中更新值而不是重新渲染完整的应用程序?
EN

Stack Overflow用户
提问于 2021-03-15 16:01:20
回答 1查看 117关注 0票数 0

在这里,我尝试使用Context-API将header组件的值更新为search组件。在我的例子中,我在header组件中有一个dropdown,我希望将dropdown值传递给搜索页面,而不重新呈现搜索组件。下面是我的示例代码

代码语言:javascript
复制
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]);
}
代码语言:javascript
复制
<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?

EN

回答 1

Stack Overflow用户

发布于 2021-03-15 17:09:24

在定义Context的值时,您需要定义值和回调函数来更改该值。我认为你应该阅读并遵循这个react文档https://reactjs.org/docs/context.html#updating-context-from-a-nested-component

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66634261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档