gpt4 book ai didi

javascript - 本地状态工作正常,但当我尝试使用 Redux 进行相同操作时,它不起作用

转载 作者:行者123 更新时间:2023-12-03 00:10:43 25 4
gpt4 key购买 nike

在这个组件上我渲染了 2 条路线。对于本地状态,它工作得很好,但我试图用 Redux 实现同样的效果,但我不知道如何将信号发送到 redux 以便更改这段代码的 index 部分状态。

这是以前的工作方式:

class MyComp extends Component {
state = {
index: 0,
routes: [
{ key: 'first', title: 'Drop-Off' },
{ key: 'second', title: 'Pick up' },
],
};

handleIndexChange = indexParam => {
const { navigation } = this.props;

this.setState({ index: indexParam });

if (indexParam) navigation.navigate('App2');
else navigation.navigate('App');
};
}

在渲染方法中:

  render() {
return (
<TabView
navigationState={this.state}
onIndexChange={this.handleIndexChange}
/>
);
}

上面的代码按预期工作。现在我需要相同的东西,但是使用 Redux,这样我可能会停止使用本地状态。行动:

import ActionTypes from '../constants/ActionTypes';

export const indexRouteAction = index => ({
type: ActionTypes.INDEX_ROUTE,
payload: {
index,
},
});

export default indexRouteAction;

reducer :

import createReducer from '../../../redux/createReducer';
import ActionTypes from '../constants/ActionTypes';

const initialState = {
navigation: {
index: 0,
routes: [
{ key: 'first', title: 'Drop-Off' },
{ key: 'second', title: 'Pick up' },
],
},
};

const handlers = {
[ActionTypes.INDEX_ROUTE](state, action) {
return {
...state,
index: action.payload.index,
};
},
};

export default createReducer(initialState, handlers);

那么现在我可以做什么来处理来自组件的数据呢?我有这样的事情:渲染方法:

  render() {
const { navigationStore } = this.props;
return (
<TabView
navigationState={navigationStore}
onIndexChange={this.handleIndexChange}
/>
);
}

我这样称呼商店:

export default compose(
connect(
store => ({
navigationStore: store.homeScreen.navigation,
}),
dispatch => ({
indexRouteActionHandler: data => {
dispatch(indexRouteAction(data));
},
}),
),
)(withNavigation(TopTabView));

这是我更改 onClick 函数索引的函数:

  handleIndexChange = indexParam => {
// BEFORE WITH STATE THIS FUNCTION WORKED WITH SETSTATE
// NOW I HAVE TO MAKE IT WORK WITH REDUX STATE
// this.setState({ index: indexParam });
const { indexRouteActionHandler, navigation } = this.props;
indexRouteActionHandler(indexParam);
if (indexParam) navigation.navigate('App2');
else navigation.navigate('App');
};

我错过了什么?

更新:

我注意到,这是我在 Redux DevTools 上看到的:

{
homeScreen: {
navigation: {
index: 0,
routes: [
{
key: 'first',
title: 'Drop-Off',
routeName: 'DropOffHome'
},
{
key: 'second',
title: 'Pick up',
routeName: 'PickupHome'
}
]
},
index: 0
}
}

我看到有 2 个索引,其中一个改变其状态的是导航外部的索引: navigation: {...}, index: 0 我需要获取导航内部的索引: 导航:{索引:0,路线:[...]}

最佳答案

您尚未在 redux 存储中正确更新状态。索引值位于navigation内部,因此您需要像

一样更新它
const handlers = {
[ActionTypes.INDEX_ROUTE](state, action) {
return {
...state,
navigation: {
...state.navigation,
index: action.payload.index,
}
};
},
};

关于javascript - 本地状态工作正常,但当我尝试使用 Redux 进行相同操作时,它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54743170/

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