我正在尝试使用React Context API重新编写我的应用程序,但遇到了下一个问题-我想要通过Provider传递给Consumer的值未传递。
初始状态:
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>
);
}
}
我没有任何错误,但是也没有Context值。
答案 0 :(得分:0)
您还需要在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>