我正在从我的应用程序提供商处接收状态,但我需要 const 或子组件状态中的状态。但我找不到办法做到这一点。
例如我想要这样的东西:
const admin = <MyContext.Consumer>{() =>
this.setState({username: (context =>
context.state.name)})}
</MyContext.Consumer>;
或者:
const admin = <MyContext.Consumer>{(context) => context.state.name}</MyContext.Consumer>
admin 将包含州名称的值。
我知道我的方法行不通,但是我应该采取什么方法来制作这样的东西?
最佳答案
<MyContext.Consumer>
只能在渲染中使用,并且它提供的值只能在您传递给它的子函数中访问。如果您需要访问它的其他生命周期 Hook ,例如使用它调用 setState,有几个选项。如果您使用的是 React 16.6(我撰写本文时的最新版本),您可以使用 static contextType (请注意,它是 contextType 单数,而不是 contextTypes 复数)
export class MyComponent extends Component {
static contextType = MyContext;
componentDidMount() {
// value is available on this.context, so you can do things like:
this.setState({ username: this.context.state.name });
}
}
在 React 16.6 之前,您可以将组件包装在另一个组件中,然后通过主组件上的 props 与值进行交互:
export const MyComponent = props => (
<MyContext.Consumer>
{context => <InnerComponent someExtraProp={context} {...props} />}
</MyContext.Consumer>
);
class InnerComponent extends Component {
componentDidMount() {
this.setState({
username: this.props.someExtraProp.state.name,
});
}
}
关于javascript - 将 React 上下文提供者的状态放入 const 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585272/