使用redux操作,调度无法正常工作

时间:2019-10-28 04:24:01

标签: react-native redux react-redux redux-thunk

我结合了我的反应性还原。

这是我的App.js

costOfItem = int(input('What is the price of the item? '))
quantityOfItem = int(input('What is the quantity desired? '))
sales_tax = input('Is this item taxable? ')


if costOfItem <= 25:
    shipping = 6
    subTotal = costOfItem * quantityOfItem
    salesTax = subTotal * 0.07
    totalCost = shipping + subTotal + salesTax
    print('Subtotal is $', format(subTotal, ',.2f'), sep='')
    print('Sales tax is $', format(salesTax, ',.2f'), sep='')
    print('Shipping is $', format(shipping, ',.2f'), sep='')
    print('Total cost is $', format(totalCost, ',.2f'), sep='')

elif costOfItem >= 25:
    shipping = 0
    subTotal = costOfItem * quantityOfItem
    salesTax = 0
    totalCost = shipping + subTotal + salesTax
    print('Subtotal is $', format(subTotal, ',.2f'), sep='')
    print('Sales tax is $', format(salesTax, ',.2f'), sep='')
    print('Shipping is $', format(shipping, ',.2f'), sep='')
    print('Total cost is $', format(totalCost, ',.2f'), sep='')

src / reducers / index.js

import React from 'react';
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { compose, createStore, applyMiddleware } from 'redux';
import reducers from './src/reducers';
import AppContainer from './src/navigator'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const App: () => React$Node = () => {

  const store = createStore(reducers, {}, composeEnhancers(applyMiddleware(ReduxThunk)));

  return (
    <Provider store={store}>
      <AppContainer />   
    </Provider>     
  );
};

export default App;

如果我使用动作import { combineReducers } from 'redux'; import LoginReducer from './LoginReducer'; export default combineReducers({ LoginRedux: LoginReducer }); ,则可以看到login(),但是看不到login action start

dispatch start

如果我 import React from 'react'; import { Text, View, TouchableOpacity, } from 'react-native'; import { connect } from 'react-redux'; import { login } from '../actions'; const LoginScreen = ({ navigation }) => { // console.log('see my test value', testValue) return ( <View> <TouchableOpacity onPress={() => { login(); } }> <View> <Text>LOGIN</Text> </View> </TouchableOpacity> </View> </View> ); } const mapStateToProps = (state) => { const { testValue } = state.LoginRedux; console.log('mapStateToProps testValue =>', testValue); return { testValue }; }; export default connect(mapStateToProps, { login })(LoginScreen); ,它将显示调度未定义。

console.log(dispatch)

src / reducers / LoginReducer.js

import { LOGIN } from './types';

export const login = () => {
  console.log('login action start')
  return (dispatch) => {
    console.log('dispatch start');
    // console.log(dispatch);
    dispatch({ type: LOGIN, testValue: 'I am test' });
  };  
};

我不知道为什么我的动作分配不起作用。我设置错了吗?

任何帮助将不胜感激。

根据Zaki Obeid的帮助,我这样更新: 动作代码:

import { LOGIN } from '../actions/types';

const INITIAL_STATE = {
  testValue: ''
};

export default (state = INITIAL_STATE, action) => {
  console.log('reducer =>', action); // I can't see the console.log
  switch (action.type) {
    case LOGIN:
      return {
        ...state,
        testValue: action.testValue
      };
    default:
      return state;
    }
};

功能组件代码:

export const login = () => { 
  console.log('login !');
  return { type: LOGIN }; 
}; 

3 个答案:

答案 0 :(得分:1)

在react-redux应用程序中,您可以通过直接获取存储对象的所有权(store.dispatch或通过react-redux connect函数来获得调度功能,后者将提供调度作为您编写的函数的参数,然后再连接到组件

import { connect } from 'react-redux';

const mapStateToProps = ...

const mapDispatchToProps = (dispatch) => {
    return {
        someHandle: () => dispatch(myActionCreator())
    }
}

export const connect(mapStateToProps, mapDispatchToProps)(MyComponent)

您不能只是凭空呼叫调度-它不是全局函数。

答案 1 :(得分:1)

似乎您正在直接使用登录功能。您将不得不使用道具。只需通过道具更改名称即可混淆和使用。

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

export default combineReducers({
  LoginRedux: LoginReducer
});
If I use my action login(), I can see login action start, but I can't see dispatch start

    import React from 'react';
    import { 
      Text, 
      View, 
      TouchableOpacity,
    } from 'react-native';
    import { connect } from 'react-redux';
    import { login } from '../actions';

    const LoginScreen = ({ navigation, userLogin }) => {

      // console.log('see my test value', testValue)

      return (
        <View>
          <TouchableOpacity 
            onPress={() => {
              userLogin();
            }
          }>
            <View>
              <Text>LOGIN</Text>
            </View>
          </TouchableOpacity>

        </View>
       </View>
      );
    }

    const mapStateToProps = (state) => {
      const { testValue } = state.LoginRedux;
      console.log('mapStateToProps testValue =>', testValue);
      return { testValue };
    };

export default connect(mapStateToProps, { userLogin:login })(LoginScreen);

答案 2 :(得分:1)

在LoginScreen组件中

您将需要添加mapDispatchToProps

const mapDispatchToProps = dispatch => ({
  // you will use this to pass it to the props of your component
  login: () => dispatch(login()),
});


export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen);

然后

您将需要按照以下步骤破坏道具:

const LoginScreen = ({ navigation, login }) => {
  // your code
}

在actions.js

您在此处使用调度的方式需要一个库redux-thunk,该库用于异步调用。

,正常的操作应该可以为您完成工作:

   export const login = () => ({
     type: LOGIN,
     testValue: 'I am test' 
})

我希望这会有用,并且可以解决您的问题, 祝你有美好的一天。