【问题标题】:How can I render a different component based on a value from the Context API?如何根据 Context API 中的值呈现不同的组件?
【发布时间】:2019-07-10 02:19:33
【问题描述】:

所以我有这个导航器组件,根据来自另一个组件的值,我需要显示不同的底部导航。

现在我在上下文消费者中遇到了一个错误,这里:

import { ThemeProvider, ThemeConsumer } from '../context/some';

const SelectedRoute = () => (
  <ThemeConsumer>
    {context => (context ? MainTabNavigator : PickupNavigator)}
  </ThemeConsumer>
);


export default createAppContainer(
  createSwitchNavigator(
    {
      App: SelectedRoute,
    },
  ),
);

这是我唯一需要创建的上下文:

const ThemeContext = React.createContext(0);

export const ThemeProvider = ThemeContext.Provider;
export const ThemeConsumer = ThemeContext.Consumer;

我收到此警告:

警告:函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。

我能做些什么来正确渲染我需要的东西?

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    您希望将 JSX 从作为子函数提供给 ThemeConsumer 的函数返回,而不仅仅是返回一个组件。

    const SelectedRoute = () => (
      <ThemeConsumer>
        {context => (context ? <MainTabNavigator /> : <PickupNavigator />)}
      </ThemeConsumer>
    );
    

    【讨论】:

    • 现在我在导航器上遇到错误>是的。但现在我收到关于导航的错误 -> Invariant Violation: The navigation prop is missing for this navigator. In react-navigation 3 you must set up your app container directly. More info: https://reactnavigation.org/docs/en/app-containers.html 该死的
    • @Reacting 是的,this might help with that.
    • 是的,但事实上我不需要ThemeConsumer,我只需要来自context 的值。有没有办法让我无需致电ThemeConsumer 即可访问它?
    【解决方案2】:

    我没有运行示例,只是从文档中提出建议。我认为解释很清楚,但我可能错了。

    只需在一个单独的文件中定义一个上下文变量,在你的情况下是这样的:

    export const IndexContext = React.createContext({
        indexValue: value,
        toggleNavigator: () => {},
    });
    

    在您的组件(接收 indexValue)中,您可以使用上下文值并相应地切换:

    <ThemeContext.Consumer>
      {({indexValue, toggleNavigator}) => (
          // your component which uses the theme 
      )}
    </ThemeContext.Consumer>
    

    由于您的组件 A 是一个有状态的组件,您可以在那里处理更改并更新上下文值。

    class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.toggleIndex = () => {
            this.setState({ index });
            this.handleStateIndexChange();
            MY_CONTEXT = index;
        };
    
        // State also contains the updater function so it will
        // be passed down into the context provider
        this.state = {
          index: index,
          toggleIndex: this.toggleIndex,
        };
      }
    
      render() {
        // The entire state is passed to the provider
        return (
          <IndexContext.Provider value={this.state}>
            <Content />
          </IndexContext.Provider>
        );
      }
    }
    

    我希望这会有所帮助。

    【讨论】:

    • 是的,但事实上我不需要ThemeConsumer,我需要的只是来自上下文的值。有没有办法让我无需拨打ThemeConsumer就可以访问它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多