我正在尝试从提供程序内部更改状态。问题在于它是在第二次单击而不是在第一次单击时设置状态。在组件中,我有一个条件,即它根据nowPlay的状态显示一个或其他内容,即使状态在如果发生第二次点击,我的内部不会改变。
代码,在这里:
组件
import Context from '../../services/contextFile';
export default class Home extends React.Component {
render() {
return (
<Context.Consumer>{
value => {
const { state, actions } = value
return (
<div className="container">
{
value.state.nowPlaying ? <div className='btn-live'><p>LIVE</p></div> : <p>NOT</p>
}
<button onClick={value.actions.onPlayChange}> change! </button>
</div>
)
}
}</Context.Consumer>
)
}
}
contentFile
const Context = React.createContext()
class ContextProvider extends Component {
state = {
nowPLaying : false
}
handlePlay = () => {
console.log(this.state.nowPLaying) // fisrt click: false, second click true
this.setState({ nowPLaying: true })
}
render() {
const { children } = this.props
return (
<ContextProvider.Provider
value={{
state: this.state,
actions: {
onPlayChange: this.handlePlay,
},
}}
>
{children}
</ContextProvider.Provider>
)
}
}
export {ContextProvider, Context as default}