我试图听取当前导航参数的变化。
我尝试了以下代码:
@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。
如何观察当前的导航参数?
谢谢你。
答案 0 :(得分:0)
这可能是因为导航状态不可观察。
@computed
属性仅在触发其中一个已使用的@observable
属性后触发重新评估。
您的渲染状态确实会在更改道具时被触发,因此渲染日志会被触发而不是mobx自动运行(渲染函数是反应物并且在此处触发的道具已更改,自动运行仅在mobx可观察状态的变化时触发)。 / p>
因此,请确保this.props.navigation.state.params
为@observable
。最好从根本上观察它。
简而言之:你不能在React.State上使用@mobx.computed
。没有观察到反应状态,因此不会触发Mobx状态的任何变化!
请在此处查看有关如何在反应组件中直接使用Mobx State的示例:https://alexhisen.gitbooks.io/mobx-recipes/content/use-observables-instead-of-state-in-react-components.html