React Native Redux Reducer无法正常工作

时间:2018-05-06 07:23:14

标签: javascript reactjs react-native redux react-redux

我正在尝试将redux实现为一个相对简单的应用程序,但是我的操作似乎并没有正确地触发reducer。通过控制台日志记录,操作似乎正在触发,但相应的reducer未被执行。

App.js:

import {Provider} from 'react-redux';
import configureStore from './src/config/configureStore.js';
const store = configureStore();

export default class App extends React.Component {    
render() {
return (
  <Provider store = {store}>
      <RootStack />
  </Provider>
);
}
}

configureStore.js:

import {createStore, applyMiddleware} from 'redux';
import reducers from '../reducers';
import thunk from 'redux-thunk';

export default function configureStore(initialState) {
  const store = createStore (
    reducers,
    applyMiddleware(thunk)
  );
  return store;
}

动作/ index.js:

export const saveRisk = (payload) => {
  console.log('saved RISK!');
  return (dispatch) => {
    dispatch({type: 'risk_chosen',payload: payload});
  }
}

减速器/ index.js:

import { combineReducers } from 'redux';
import RiskReducer from './RiskReducer';

export default combineReducers({
  risk_level: RiskReducer
});

RiskReducer.js

const INITIAL_STATE = {risk_level: false};
export default (risk = INITIAL_STATE, action) => {
  if(action.type === 'risk_chosen') {
    console.log('RISK REDUCER SUCCESSFUL')
    return {
      ...risk, risk_level: action.payload
    };
  }
  console.log('REDUCER RISK:');
  console.log(risk);
  return risk;
}

RiskTolerance.js(RootStack中使用redux的子组件):

import { connect } from 'react-redux';
import {saveRisk} from '../../actions'
@connect(state => ({risk_level: state.risk_level.risk_level}, {saveRisk}))
export default class RiskTolerance extends React.Component {
 //   ...
  componentDidMount(){
    console.log(this.props.risk_level);
 // ^^returns undefined, despite the reducer initializing it to "false"
    let riskVal = 'something'
    this.props.saveRisk(riskVal)
  }
 //   ...
}

编辑:我已将reducer中的初始值更改为适当的对象,但在调用操作后,我的reducer仍然无法正常工作。有任何想法吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

你的减速机有初始状态的问题。进行如下所示的更改:

INITIAL_STATE = { risk_level: false }

答案 1 :(得分:1)

在调用我需要写的动作时想出来:

this.props.dispatch(this.props.saveRisk(riskVal))

感谢大家的帮助!