Javascript 对此不作出反应';有时在setState的回调中不工作
假设 我应该什么时候使用Javascript 对此不作出反应';有时在setState的回调中不工作,javascript,reactjs,setstate,Javascript,Reactjs,Setstate,假设 我应该什么时候使用 callback = () => { ... } 我应该什么时候使用 this.setState({...}, this.callback); 确保this在this.callback方法中仍然有效 有一些基本的规则我们应该遵循吗?这两个规则是等效的,取决于你如何设置你班上的其他同学 如果希望此在回调方法中有效,则有2个选项: I)在构造函数中绑定回调: this.setState({...}, () => { this.callback(); });
callback = () => { ... }
我应该什么时候使用
this.setState({...}, this.callback);
确保this在this.callback方法中仍然有效
有一些基本的规则我们应该遵循吗?这两个规则是等效的,取决于你如何设置你班上的其他同学
如果希望此
在回调
方法中有效,则有2个选项:
I)在构造函数中绑定回调:
this.setState({...}, () => { this.callback(); });
II)将回调声明为lambda(我通常更喜欢这种方法,因为不会忘记绑定它)
我一开始问这个问题的原因是我遇到了这样的情况:
如您所见,reloadService
在更新参数时使用。首先,我使用了版本-1,因为我计划以后使用这些值,作为一个遵循规则的保守程序员,我打算在方法的一开始就声明要使用的变量,然后我陷入了这个混乱——潜伏的错误
正如预期的那样,我总是在case后面遇到一个状态,因为声明的变量将被更新,但回调将引用由于闭包机制而过时的旧变量。但是如果我们直接将回调提取到成员方法中,它将正常工作
componentWillReceiveProps(nextProps) {
const { envId, serviceName } = this.props;
if (envId !== nextProps.envId || serviceName !== nextProps.serviceName) {
this.reloadService();
}
}
reloadService = () => {
const { envId, serviceName, dispatch } = this.props; // version - 1
this.setState({ loading: true }, () => {
const { envId, serviceName, dispatch } = this.props; // version -2
dispatch(ProdcutActions.fetchServiceDetail(envId, serviceName))
.then(response => response.data)
.then((serviceVo) => {
this.setState({ serviceVo, loading: false });
});
});
}
或者你可以选择版本-2,如果你不像我一样保守的话 好问题。我期待答案,我怀疑答案将与回调函数正在做的事情有关,例如,如果它正在调用另一个方法抱歉,请添加后续操作。实际上,它已经是箭头函数
。那么在这两种情况下,上下文都是您所期望的。你有没有一个具体的例子,它没有按预期工作?真的很抱歉,它发生在几周前,我现在找不到它。如果我再次遇到,我会更新帖子。谢谢你,克鲁乔
class YourComp extends React.Component {
callback = () => { ... your code ... }
}
componentWillReceiveProps(nextProps) {
const { envId, serviceName } = this.props;
if (envId !== nextProps.envId || serviceName !== nextProps.serviceName) {
this.reloadService();
}
}
reloadService = () => {
const { envId, serviceName, dispatch } = this.props; // version - 1
this.setState({ loading: true }, () => {
const { envId, serviceName, dispatch } = this.props; // version -2
dispatch(ProdcutActions.fetchServiceDetail(envId, serviceName))
.then(response => response.data)
.then((serviceVo) => {
this.setState({ serviceVo, loading: false });
});
});
}
componentWillReceiveProps(nextProps) {
const { envId, serviceName } = this.props;
if (envId !== nextProps.envId || serviceName !== nextProps.serviceName) {
this.reloadService();
}
}
reloadService = () => {
this.setState({ loading: true }, this.updateServiceDo);
}
updateServiceDo = () => {
const { envId, serviceName, dispatch } = this.props;
dispatch(ProdcutActions.fetchServiceDetail(envId, serviceName))
.then(response => response.data)
.then((serviceVo) => {
this.setState({ serviceVo, loading: false });
});
}