所以我使用 React 的上下文,因为我必须以相反的方向更改状态。
例如:
App.js (有状态) <--- 我的组件 (更改应用程序中的状态.js)
我知道如何使用 onClick 事件来做到这一点。但是,我无法理解如何在 componentDidMount() 中执行此操作。我创建了一个基本示例来说明我想要实现的目标:
MyComponent.js
import { MyConsumer } from '../App.js';
export default class MyComponent extends Component {
componentDidMount() {
// TRYING TO CHANGE STATE IN COMPONENTDIDMOUNT
<MyConsumer>
{({ actions }) => actions.setMyState(true)}
</MyConsumer>
}
render() {
return (
<SearchConsumer>
{({ actions }) => {
return (
<div onClick={() => actions.setMyState(true)}>
My content
</div>
)
}}
</SearchConsumer>
)
}
}
App.js
export const SearchContext = createContext();
export const SearchProvider = SearchContext.Provider;
export const SearchConsumer = SearchContext.Consumer;
class App extends Component {
constructor (props) {
super (props)
this.state = {
setMyState: 0,
}
}
render(){
return(
<SearchProvider value={
{
actions: {
setMyState: event => {
this.setState({ setMyState: 0 })
},
}
}
}>
<Switch>
<Route
exact path='/' render={(props) => <MyComponent />}
/>
</Switch>
</SearchProvider>
)
}
}
最佳答案
如果你使用的是react 16.6.0或更高版本并且仅使用一个上下文使用者,那么最简单的方法是使用 contextType
(请注意,这是单数,而不是复数)。这将导致 React 使该值在 this.context
上可用,然后您可以在生命周期 Hook 中使用该值。例如:
// In some other file:
export default MyContext = React.createContext();
// and in your component file
export default class MyComponent extends Component {
static contextType = MyContext;
componentDidMount() {
const { actions } = this.context;
actions.setMyState(true);
}
// ... etc
}
如果您使用的是旧版本,因此无法使用 contextType
,或者如果您需要从多个上下文中获取值,则需要将您的组件包装在另一个组件中,并且通过 prop 传递上下文。
// In some other file:
export default MyContext = React.createContext();
// and in your component file
class MyComponent extends Component {
static contextType = MyContext;
componentDidMount() {
const { actions } = this.props;
actions.setMyState(true);
}
// ... etc
}
export default props => (
<MyContext.Consumer>
{({ actions }) => (
<MyComponent actions={actions} {...props} />
)}
</MyContext.Consumer>
);
关于javascript - react : How do I use my consumer inside ComponentDidMount to change state?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54754411/