我正在尝试使用新的 ReactJs Context 作为 Redux 的替代品,但是我遇到了一个错误。
不变违规:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。
https://reactjs.org/docs/context.html
这是我包装在 MyProvider 标记中的布局代码
import React, { Component } from "react";
import { NavMenu } from "./NavMenu";
import { MyProvider } from "../contexts/context";
export class Layout extends Component {
render() {
return (
<MyProvider>
<div className="container-fluid">
<div className="row">
<div className="col-sm-3">
<NavMenu />
</div>
<div className="col-sm-9">
{this.props.children}
</div>
</div>
</div>
</MyProvider>
);
}
}
这是我要导入的上下文代码
import React, { Component } from "react";
export const MyContext = React.createContext();
export class MyProvider extends Component {
state = {
name: 'test name'
}
render() {
return (
<MyContext.Provider value="{this.state}">
{this.props.children}
</MyContext.Provider>
)
}
}
这里是提供者被消费的地方
import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { MyProvider } from "../contexts/context";
export class Counter extends Component {
render() {
return <div className="m-2">
<MyContext.Consumer>
{(c) => (<p>My name is {c.state.name}</p>)}
</MyContext.Consumer>
</div>;
}
}
任何帮助将不胜感激。