我正在使用react.js做一个小笔记应用程序,我正在使用react context api处理全局状态,这是我的context.js文件:
import React, { Component } from "react";
const Context = React.createContext();
export class Provider extends Component {
state = {
notes: [
{
id: 1,
title: "lorem",
content: "lorem ipsum dolor",
tags: "lorem, ipsum"
}
],
dispatch: action => this.setState(state => reducer(state, action))
};
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
export const Consumer = Context.Consumer;
我想从componentDidMount方法内的其他组件访问notes数组,我尝试了此代码,但没有用:
import React, { Component } from "react";
import { Consumer } from "../../context";
export default class EditNote extends Component {
componentDidMount() {
return (
<Consumer>
{value => {
const { notes } = value;
console.log(notes);
}}
</Consumer>
);
}
render() {
return null;
}
}
同一方法在render方法中可以正常工作,但是在componentDidMount内部却无法正常工作,有人可以帮助我做到这一点吗?