自动运行到当前导航参数
autorun to current navigation params
我正在尝试监听当前导航参数的变化。
我尝试了以下代码:
@observer
export default class TestScreen extends Component<PropsType> {
@computed get currParams(): ?Object {
return this.props.navigation.state.params;
}
constructor(props: PropsType) {
super(props);
setTimeout(() => {
props.navigation.setParams({ a: 'b' });
}, 1500);
this.aa = autorun(() => {
console.log('currParams', this.currParams);
console.log('a', this.currParams && this.currParams.a);
});
}
render(): React$Element<any> {
console.log('R', this.props.navigation.state.params);
return (
<View />
);
}
}
打印:
currParams undefined
a undefined
R undefined
R undefined
R {a: "b"}
R {a: "b"}
意味着屏幕呈现了新值,但自动运行没有看到参数发生变化。
如果我将 render 方法中的 console.log 更改为打印 this.currParams,它会一直打印 undefined。
如何观察当前导航参数?
谢谢你
这可能是因为导航状态不可观察。
@computed
属性仅在使用的 @observable
属性之一被触发后才触发重新评估。
您的渲染状态确实会在更改 Props 时触发,因此会触发渲染日志,但不会触发 mobx 自动运行(渲染函数是一个反应对象,在此处触发 prop 更改,自动运行仅在 mobx 可观察状态发生变化时触发) .
因此确保 this.props.navigation.state.params
是 @observable
。最好让它在根部可见。
简而言之:您不能在 React.State 上使用 @mobx.computed
。 React 状态不会被观察到,因此不会触发您的 Mobx 状态发生任何变化!
请参阅此处有关如何在 React 组件中直接使用 Mobx State 的示例:https://alexhisen.gitbooks.io/mobx-recipes/content/use-observables-instead-of-state-in-react-components.html
我正在尝试监听当前导航参数的变化。
我尝试了以下代码:
@observer
export default class TestScreen extends Component<PropsType> {
@computed get currParams(): ?Object {
return this.props.navigation.state.params;
}
constructor(props: PropsType) {
super(props);
setTimeout(() => {
props.navigation.setParams({ a: 'b' });
}, 1500);
this.aa = autorun(() => {
console.log('currParams', this.currParams);
console.log('a', this.currParams && this.currParams.a);
});
}
render(): React$Element<any> {
console.log('R', this.props.navigation.state.params);
return (
<View />
);
}
}
打印:
currParams undefined
a undefined
R undefined
R undefined
R {a: "b"}
R {a: "b"}
意味着屏幕呈现了新值,但自动运行没有看到参数发生变化。
如果我将 render 方法中的 console.log 更改为打印 this.currParams,它会一直打印 undefined。
如何观察当前导航参数?
谢谢你
这可能是因为导航状态不可观察。
@computed
属性仅在使用的 @observable
属性之一被触发后才触发重新评估。
您的渲染状态确实会在更改 Props 时触发,因此会触发渲染日志,但不会触发 mobx 自动运行(渲染函数是一个反应对象,在此处触发 prop 更改,自动运行仅在 mobx 可观察状态发生变化时触发) .
因此确保 this.props.navigation.state.params
是 @observable
。最好让它在根部可见。
简而言之:您不能在 React.State 上使用 @mobx.computed
。 React 状态不会被观察到,因此不会触发您的 Mobx 状态发生任何变化!
请参阅此处有关如何在 React 组件中直接使用 Mobx State 的示例:https://alexhisen.gitbooks.io/mobx-recipes/content/use-observables-instead-of-state-in-react-components.html