我正在尝试使用新的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>;
}
}
任何帮助将不胜感激。
答案 0 :(得分:1)
您应该使用{this.state}
作为提供者的值,而不是"{this.state}"
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>
);
}
}
您还必须使用MyContext.Consumer
组件才能使用提供者提供的value
,并且该组件将功能作为子组件。
import { MyProvider, MyContext } from "../contexts/context";
export class Layout extends Component {
render() {
return (
<MyProvider>
<MyContext.Consumer>
{value => (
<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>
)}
</MyContext.Consumer>
</MyProvider>
);
}
}
答案 1 :(得分:1)
让我提供另一个答案。这类似于@Tholle的,但我认为它更接近您的意图。如果没有,请考虑将其作为简单的替代方法。
const MyContext = React.createContext()
class MyProvider extends React.Component {
state = {
name: 'test name'
}
render() {
return (
<MyContext.Provider value={this.state}>
{this.props.children}
</MyContext.Provider>
)
}
}
class Layout extends React.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>
);
}
}
class Counter extends React.Component {
render() {
return <div className="m-2">
<MyContext.Consumer>
{c => <p>My name is {c.name}</p>}
</MyContext.Consumer>
</div>;
}
}
ReactDOM.render(<Layout><Counter /></Layout>, document.getElementById("root"));