我正在使用react本地反应原生导航。当我从第一页移到第二页时,我的状态变化不会持久。
App.js
import React from 'react';
import { createStackNavigator } from 'react-navigation';
import { Provider } from 'react-redux';
import Home from './home/home';
import Recommend from './recommend/recommend';
import store from '../redux/store';
const RootStack = createStackNavigator(
{
Home: { screen: Home },
Recommend: { screen: Recommend }
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<RootStack />
</Provider>
);
}
}
reduer:
import { combineReducers } from 'redux';
import { DATA_AVAILABLE, UPDATE_PREFERANCE } from '../actions/index';
const dataState = { data: { college: 'ABC', major: '123' } };
const dataReducer = (state = dataState, action) => {
switch (action.type) {
case DATA_AVAILABLE:
state = Object.assign({}, state);
return state;
case UPDATE_PREFERANCE:
console.log('update pref');
return {
...state,
data: {
college: action.payload.collegeName,
major: action.payload.majorName
}
}
default:
return state;
}
};
const rootReducer = combineReducers({
dataReducer
});
export default rootReducer;
主页组件:
import React, { Component } from 'react';
import {
Container,
Header,
Title,
Content,
Text,
Button,
Icon,
Footer,
FooterTab,
Left,
Right,
Item,
Input,
View,
Picker
} from 'native-base';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import styles from './style';
import * as Actions from '../../redux/actions/index';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
college: '',
major: ''
};
const currentYear = new Date().getFullYear();
this.yearList = [];
this.yearList.push(currentYear);
for (let i = 0; i <= 10; i++) {
this.yearList.push(currentYear + i);
}
}
componentDidMount() {
this.props.getData();
}
componentWillReceiveProps(nextProps) {
this.setState({ college: nextProps.data.college, major: nextProps.data.major });
}
onValueChange(value: string) {
this.setState({
selected: value
});
}
navigateToRecommend() {
this.props.navigation.navigate('Recommend');
}
handleChange(text, key) {
this.setState({ [key]: text });
this.props.updateUserPreference(this.state.college, this.state.major);
}
render() {
return (
<Container style={styles.container}>
...........render logic
</Container>
);
}
}
function mapStateToProps(state, props) {
return {
data: state.dataReducer.data
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(Actions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
当我从Home移至推荐页面时,默认状态为空。此外,当调用更新首选项时,状态不会在主组件中发生变化。
编辑:
存储文件:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers/index'; //Import the reducer
export default createStore(reducers, applyMiddleware(thunk));