值不会通过React上下文API传递



我正在尝试使用React Context API重写我的应用程序,但面临下一个问题 - 我想通过提供商将提供商传递给消费者的价值。<<<<<<<<<<

初始状态:

let initialState = {
    ve: 'randomValue'
};
export default initialState;

提供者:

import React, {Component} from 'react';
import MyContext from './myContext';
import initialState from './initialState';
class MyProvider extends Component{
constructor(props) {
    super(props);
    this.state = initialState;
}
render() {
    return(
        <MyContext.Provider value={{
            state: this.state,
        }}>
            {this.props.children}
        </MyContext.Provider>
    )
    }
};
export default MyProvider;

消费者:

import React, {Component} from 'react';
import {Text, View} from 'react-native';
import MyContext from './Context/myContext';
export default class App extends Component {
  render() {
    return (
      <MyContext.Consumer>
        {context => (
          <View>
            <Text>
              {context}
            </Text>
          </View>
        )}
      </MyContext.Consumer>
    );
  }
}

我没有任何错误,但也没有上下文值。

您还需要使用Provider组件也需要MyContext.Consumer组件上方的位置。

示例

const initialState = {
  ve: "randomValue"
};
const MyContext = React.createContext();
class MyProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = initialState;
  }
  render() {
    return (
      <MyContext.Provider
        value={{
          state: this.state
        }}
      >
        {this.props.children}
      </MyContext.Provider>
    );
  }
}
class App extends React.Component {
  render() {
    return (
      <MyProvider>
        <MyContext.Consumer>
          {context => <div>{JSON.stringify(context)}</div>}
        </MyContext.Consumer>
      </MyProvider>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

相关内容

  • 没有找到相关文章

最新更新