[英]React: How do I use my consumer inside ComponentDidMount to change state?
所以我使用React的上下文,因為我必須沿相反的方向更改狀態。
例如:
App.js (具有狀態) <--- 我的組件 (更改App.js中的狀態)
我知道如何使用onClick事件來執行此操作。 但是,我無法理解如何在componentDidMount()中執行此操作。 我創建了一個基本示例來說明我要實現的目標:
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>
)
}
}
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
(請注意,它是單數形式,而不是復數形式)。 這將導致做出反應,使此值在this.context
可用,然后可以在生命周期掛鈎中使用它。 例如:
// 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>
);
感謝尼古拉斯·塔的回答,我用一個想法解決了我的問題。 我沒有在React中使用contextType,而是只是將我的操作作為prop傳遞給了另一個組件。 這樣,如果我只是將其作為道具傳遞,我仍然可以使用我的消費者的所有東西。
class MyComponent extends Component {
componentDidMount() {
this.props.actions.setMyState(true);
}
// ... etc
}
export default class MyComponentTwo extends Component {
render(){
return(
<MyConsumer>
{({ actions }) => (
<MyComponent actions={actions}/>
)}
</MyConsumer>
)
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.