gpt4 book ai didi

react-native - react native + Redux : How to subscribe to changes in state?

转载 作者:行者123 更新时间:2023-12-02 04:01:29 24 4
gpt4 key购买 nike

我有一个组件,我想在状态发生变化时调用一个方法来检查状态。这是我的组件,带有一个虚拟方法来演示我想要执行的操作(如果 onboarding.show === false,则在屏幕外设置 View 动画):

export class Onboarding extends Component {

animateView() {
// i want to call this method when
// the state changes
// something like;
if (!this.props.onboarding.show) {
Animated.spring(...);
}
}

render() {
const { onboarding, finish } = this.props;

return (
<Animated.View>
...
</Animated.View>
);
}
}

...

export default connect(
state => {
return {
onboarding: state.onboarding,
};
},
dispatch => {
return {
};
}
)(Onboarding);

有没有办法订阅状态的变化?

==更新==

根据要求,这是我的 SlideOffScreen 方法的作用:

  slideOffScreen() {
Animated.timing(this.state.offsetX, {
toValue: -Dimensions.get('window').width,
duration: 350,
easing: Easing.elastic(),
}).start();
}

最佳答案

react-redux connect 方法使用容器组件包装该组件,该容器组件可以感知存储的状态更改。每当状态发生变化时,connect 都会重新渲染包装的组件(在您的情况下为 Onboarding)。

根据redux docs :

Technically, a container component is just a React component that uses store.subscribe() to read a part of the Redux state tree and supply props to a presentational component it renders. You could write a container component by hand, but we suggest instead generating container components with the React Redux library's connect() function, which provides many useful optimizations to prevent unnecessary re-renders.

如果状态更改时您的组件没有重新渲染,请检查您是否没有改变状态而不是替换它。 Redux 通过浅层比较旧状态和新状态(仅比较引用,而不比较值)来检查状态是否发生变化。

例如,要将一项添加到数组中,您不能使用array.push(item),因为这不会创建新数组,而只会改变现有数组。相反,您必须使用类似 array.concat(item) 的东西,它确实可以。

要更新对象,您可以在 handling actios 下的 redux 文档中查看例如,您可以看到创建一个新状态:

We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead.

关于react-native - react native + Redux : How to subscribe to changes in state?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41684009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com