简体   繁体   English

在 React 中将多个值和设置器对传递给 Context.Provider

[英]Passing multiple value and setter pairs to Context.Provider in React

All the documentation and blog posts I've managed to find so far only deals with a single [value, setValue] pair scenario.到目前为止,我设法找到的所有文档和博客文章都只涉及单个 [value, setValue] 对场景。 In my case I would like/need to pass multiple pairs of [value, setValue] variables to a Provider using the useContext hook.在我的情况下,我希望/需要使用 useContext 挂钩将多对 [value, setValue] 变量传递给提供者。

Here is the typical example I setup in CodePen: https://codepen.io/nardove/pen/XWrZRoE?editors=0011这是我在 CodePen 中设置的典型示例: https://codepen.io/nardove/pen/XWrZRoE?editors=0011

const App = () => {
    return(
        <div>
            <MyProvider>
                <ComponentA />
            </MyProvider>
        </div>
    );
}

const MyContext = React.createContext();
const MyProvider = (props) => {
    const [value, setValue] = React.useState("foo");
    return(
        <MyContext.Provider value={[value, setValue]}>
            {props.children}
        </MyContext.Provider>
    );
}

const ComponentA = () => {
const [value, setValue] = React.useContext(MyContext);
    return(
        <div>
            <h1>
                The value is: {value}
            </h1>
        </div>
    );
}

ReactDOM.render(<App /> , document.getElementById('app'));

If you can share any ideas on how pass multiple [value, setValue] pairs to the Provider or an alternative to my problem will be much appreciated如果您可以就如何将多个 [value, setValue] 对传递给 Provider 或我的问题的替代方法分享任何想法,将不胜感激

Context.Provider accepts any value, so you can try passing an object: Context.Provider接受任何值,因此您可以尝试传递一个对象:

<MyContext.Provider
  value={{ value: [value, setValue], value2: [value2, setValue2] }}
>
  {props.children}
</MyContext.Provider>;
const App = () => {
  return (
    <MyProvider>
      <ComponentA />
    </MyProvider>
  );
};

const MyContext = React.createContext();

const MyProvider = props => {
  const [value, setValue] = React.useState("foo");
  const [value2, setValue2] = React.useState("goo");

  return (
    <MyContext.Provider
      value={{ value: [value, setValue], value2: [value2, setValue2] }}
    >
      {props.children}
    </MyContext.Provider>
  );
};

const ComponentA = () => {
  const { value, value2 } = React.useContext(MyContext);
  const [stateValue, setStateValue] = value;
  const [stateValue2, setStateValue2] = value2;

  return (
    <div>
      <h1>The value is: {stateValue}</h1>
      <h1>The value2 is: {stateValue2}</h1>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("app"));

Notice that there is a caveat when trying to optimize useless renders (be sure you not just optimizing prematurely ): there is no render bailout for Context Consumers .请注意,在尝试优化无用的渲染时有一个警告(确保您不是过早地优化): Context Consumers 没有渲染救助

As for v17, may be change in near future.至于 v17,可能会在不久的将来发生变化。

To pass in multiple state values to a provider, you just need to create another state object and pass it in.要将多个状态值传递给提供者,您只需要创建另一个状态对象并将其传入。

But inlining these comes with a caveat mentioned in the docs.但是内联这些伴随着文档中提到的警告 Since the object (and arrays) in render are created every render, they lose the referential equality and hance any components connected to this context will need to refresh.由于渲染中的对象(和数组)是在每次渲染时创建的,因此它们失去了引用相等性,因此连接到此上下文的任何组件都需要刷新。

To get around this in a functional component, you can use useMemo to memoise the value and refresh only when one of these values change.要在功能组件中解决此问题,您可以使用useMemo来记住值并仅在这些值之一更改时刷新。

const MyContext = React.createContext();
const MyProvider = (props) => {
    const [valueA, setValueA] = React.useState("foo");
    const [valueB, setValueB] = React.useState("bar");
    const providerValue = React.useMemo(() => ({
        valueA, setValueA,
        valueB, setValueB,
    }), [valueA, valueB]);
    return(
        <MyContext.Provider value={providerValue}>
            {props.children}
        </MyContext.Provider>
    );
}

You can send values as shown below.您可以发送如下所示的值。 I have sent demo1, setdemo1, demo2, and setdemo2.我已经发送了 demo1、setdemo1、demo2 和 setdemo2。 Inside the {{}} inside exportValues.provider It worked for me在 exportValues.provider 里面的 {{}} 里面它对我有用

import {View, Text} from 'react-native';
import React, {createContext, useState} from 'react';

export const exportValues = createContext();

const ContextTab = ({children}) => {
  const [demo1, setdemo1] = useState([]);
  const [demo2, setdemo2] = useState([]);
  return (
    <exportValues.Provider
      value={{demo1, setdemo1,demo2, setdemo2}}>
      {children}
    </exportValues.Provider>
  );
};

export default ContextTab;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React context.provider不会更改默认值 - React context.provider doesn't change the default value 为什么 React Context.Provider 是必需的(或有用的)? - Why Is React Context.Provider Necessary (Or useful)? React Native Context - 从渲染之外的 Context.provider 中检索值 function - React Native Context - retrieve the value from Context.provider outside of the render function React - value 属性是必需的<Context.Provider> . 你是拼错了还是忘记通过了? - React - The value prop is required for the <Context.Provider>. Did you misspell it or forget to pass it? 如何访问react Context.Provider值内的另一个函数? - How can I access another function inside the react Context.Provider value? 如何在 react 和 typescript 中使用 context.provider 设置 state? - How to set the state using context.provider in react and typescript? 当我更新 context.provider 的值时,子组件不会改变颜色 - When I update my context.provider's value, the child components don't change color React Context Provider没有传递值 - React Context Provider is not passing the values 我正在尝试使用挂钩来管理Context.Provider的状态 - I am attempting to use hooks to manage the state of Context.Provider 用它包装我的应用程序组件时 Context.provider 抛出错误 - Context.provider throw error when wrapping my app component with it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM