道具召唤后没有派遣到减速器的动作

时间:2019-08-29 08:32:13

标签: react-native redux react-redux

我是redux的新手,正在尝试制作一个简单的本机应用程序。

动作被映射到道具(mapDispatchToProps),但是没有被分派给减速器。当我在Action Creators中执行console.log()时,它们被调用,但是当我在CounterReducer中进行console.log()时,它们未被调用。

App.js

class App extends React.Component {

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

export default App;

HomeScreen.js

class HomeScreen extends React.Component {
  incrementCounter = () => {
    this.props.incrementCounter();
  };

  render() {
    return (
      <View style={styles.mainContainer}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>{this.props.counter}</Text>
        <Button title="Click me " onPress={this.incrementCounter} />
        <Button
          title="Create Counter"
          onPress={() => {
            this.props.createCounter(5);
          }}
        />
      </View>
    );
  }
}

const mapStateToProps = state => ({
  counter: state.counter
});

const mapDispatchToProps = dispatch => ({
  incrementCounter: incrementCounter,
  createCounter: createCounter
});

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

store.js


const reducers = combineReducers({
    counterReducer
})

const store = createStore(reducers)

export default store;

counterReducer.js


const counterReducer = (state = {}, action) => {
  switch (action.type) {
    case actionTypes.CREATE_COUNTER:
      state.counter = action.payload;
      return { ...state };
    case actionTypes.INCREMENT_COUNTER:
      state.counter++;
      return { ...state };
    default:
      return { ...state };
  }
};

export default counterReducer;

actions.js

export const actionTypes = {
    INCREMENT_COUNTER: "INCREMENT_COUNTER",
    CREATE_COUNTER: "CREATE_COUNTER",
}

export const incrementCounter = () => {
  return {
    type: actionTypes.INCREMENT_COUNTER
  };
};

export const createCounter = value => ({
  type: actionTypes.CREATE_COUNTER,
  payload: value
});

我曾尝试在HomeScreen中执行此操作,但它给我一个错误,即操作必须是普通对象,并且即使没有任何异步操作,也必须将中间件用于异步操作。


const mapDispatchToProps = dispatch => ({
  incrementCounter: () => dispatch(incrementCounter),
  createCounter: () => dispatch(createCounter)
});

2 个答案:

答案 0 :(得分:0)

您可以通过两种方法修改mapDispatchToProps来解决此问题。最简单的就是传递一个普通对象:

const mapDispatchToProps = {
  incrementCounter: incrementCounter,
  createCounter: createCounter
};

React-redux将自动将动作创建者绑定到dispatch

要使用其他方法,您必须像这样在调度内部调用动作创建者:

const mapDispatchToProps = dispatch => ({
  incrementCounter: () => dispatch(incrementCounter()),
  createCounter: () => dispatch(createCounter())
});

答案 1 :(得分:0)

您忘记在函数调用结束时添加括号了

喜欢这样

select * from tablename 
where ID= 7718 and name = 'Astika LLC'