使用 React.createContext 将数据从父组件状态传递到子组件



我有一个包含状态的组件,我将状态数据传递给另一个组件,我使用静态 contextType 抛出状态数据,但数据没有到达预期的组件,你认为这是怎么回事?谢谢

这是我的父组件

export const MyContext = React.createContext();
export class MerchantByPromo extends Component {
constructor(props) {
super(props);
this.state = {
dataPromo: [],
loading: true
};
}
async componentDidMount() {
const merchant_id = this.props.match.params.id_merchant
await Api.post('language/promo-voucher-by-merchant', { MERCHANT_ID: merchant_id })
.then((response) => {
if (response.data.STATUS_CODE === '200') {
this.setState({
dataPromo: response.data.DATA,
loading: false
});
}
})
}

这是我的子组件

import React, { Component } from 'react'
import { MyContext } from './MerchantByPromo'
export class MerchantByPromoDetail extends Component {
constructor(props){
super(props)
this.state = {
detailPromo:[],
}
}
UNSAFE_componentWillMount(){
let value = this.context
console.log(value)
}
componentDidMount(){
}
render() {
return (
<MyContext.Consumer>
<p>tes</p>
</MyContext.Consumer>
)
}
}

我总是收到这样的错误消息"类型错误:渲染不是函数",解决方案是什么?

<MyContext.Consumer>
{() => <p>tes</p>}
</MyContext.Consumer>

更改为此并检查

最新更新