Javascript 变量值未传入函数
你好,我是新来的。我面临一个问题,变量值没有传递给函数 这是我的密码 类Main扩展了React.Component{ 状态={ 集合类型: } getTypegetValue{ let type= ifgetValue==='win'{ 类型='win' } else ifgetValue==='lose'{ 类型='lose' } 否则{ 类型= } 返回类型 } 组件安装{ 让type=this.getType'win' 这是我的国家{ setType:type } 如果this.props.match.path=='/win'{ 这是我的国家{ 设置类型:“赢” } } 如果this.props.match.path=='/lose'{ 这是我的国家{ setType:“丢失” } } } this.props.detailthis.state.setType } this.setState是一个异步调用。当程序控件访问this.props.detail时,setState可能尚未完成。因此,您的this.state.setType可能未使用新值更新。这就是为什么您的类型具有正确的值,而您的this.state.setType没有 编辑 设置如下状态:Javascript 变量值未传入函数,javascript,reactjs,Javascript,Reactjs,你好,我是新来的。我面临一个问题,变量值没有传递给函数 这是我的密码 类Main扩展了React.Component{ 状态={ 集合类型: } getTypegetValue{ let type= ifgetValue==='win'{ 类型='win' } else ifgetValue==='lose'{ 类型='lose' } 否则{ 类型= } 返回类型 } 组件安装{ 让type=this.getType'win' 这是我的国家{ setType:type } 如果this.pro
this.setState({
setType : type
}, () => {
this.props.detail(this.state.setType)
})
setState是一个异步函数。当您调用detail函数时,时间状态不会更新,并且旧值处于状态
请写一次清除和更新状态,并对回调进行操作
实例
在执行上述
时需要考虑的两件事 componentDidMount仅在组件装载时调用一次,而不是在后续重新呈现时调用 因此,在您的情况下,您需要使用componentWillReceiveProps/componentDidUpdate来更新match-prop更改时的状态,并在setState回调中第二次将值传递回细节,或者使用正在设置为state的存储值 类Main扩展了React.Component{ 状态={ 集合类型: } getTypegetValue{ let type= ifgetValue==='win'{ 类型='win' } else ifgetValue==='lose'{ 类型='lose' } 否则{ 类型= } 返回类型 } 组件安装{ 让type=this.getType'win' 这是我的国家{ setType:type } const newState=类型; 如果this.props.match.path=='/win'{ newState='win' } 如果this.props.match.path=='/lose'{ newState='lose' } this.setState{setType:newState}; this.props.detailnewState } componentDidUpdateprevProps{ 如果此.props.match.path!==prevProps.match.path{ const newState=this.state.setType; 如果this.props.match.path=='/win'{ newState='win' } 如果this.props.match.path=='/lose'{ newState='lose' } } this.setState{setType:newState},=>{ this.props.detailthis.state.setType }; }谢谢你的时间和回答。我怎样才能解决这个问题?我对JS完全是新手。
componentDidMount(){
let type = this.getType('win')
if(this.props.match.path === '/win'){
type = 'win'
}
if(this.props.match.path === '/lose'){
type = 'lose'
}
this.setState({
setType : type
}, () => {
this.props.detail(this.state.setType)
})
}