React Native Redux调度不起作用,但没有错误

时间:2020-10-26 00:11:40

标签: javascript reactjs react-native redux

我似乎无法弄清为什么即使我调度正确的操作类型也无法更新计数器,而它们却处于INCREMENT和DECREMENT状态之内。我尝试传递mapDispatchToProps并将函数放入该函数中,但仍然遇到相同的问题,由于某种原因没有任何状态更新。

索引:

import {createStore} from 'redux';
import {Provider} from 'react-redux';
import {reducer} from './src/reducers/counter';

const store = createStore(reducer);

const Main = () => (
  <Provider store={store}>
    <App />
  </Provider>
);

AppRegistry.registerComponent(appName, () => Main);

应用

import {connect} from 'react-redux';

// create a component
class App extends Component {
  increment = () => {
    this.props.dispatch({type: 'INCREMENT'});
  };

  decrement = () => {
    this.props.dispatch({type: 'DECREMENT'});
  };

  render() {
    return (
      <View style={styles.container}>
        <Button onClick={this.increment} title={'Add 1'} />
        <Text>Counter {this.props.count} </Text>
        <Button onClick={this.decrement} title={'Subtract 1'} />
      </View>
    );
  }
}

计数器

const initState = {
  count: 1,
};

export const reducer = (state = initState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return {
        count: state.count + 1,
      };
    case 'DECREMENT':
      return {
        count: state.count - 1,
      };
    default:
      return state;
  }
};

3 个答案:

答案 0 :(得分:1)

这是React Native应用,对吗?您的错误是您为onClick使用了Button而不是onPress。切换道具名称后,It works fine now

答案 1 :(得分:0)

您必须使用connect功能将App组件连接到redux存储。

import { connect } from 'react-redux';

// create a component
class App extends Component {
  increment = () => {
    this.props.increment();
  };

  decrement = () => {
    this.props.decrement();
  };

  render() {
    return (
      <View style={styles.container}>
        <Button onPress={this.increment} title={'Add 1'} />
        <Text>Counter {this.props.count} </Text>
        <Button onPress={this.decrement} title={'Subtract 1'} />
      </View>
    );
  }
}
const mapStateToProps = state => ({ count: state.count })
const mapDispatchToProps = dispatch => {
  return {
    increment: () => dispatch({ type: 'INCREMENT' }),
    decrement: () => dispatch({ type: 'DECREMENT' }),
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
    

答案 2 :(得分:0)

需要注意以下几点才能使其正常工作:

  1. 将道具的onClick更改为onPress
  2. 在App Component中创建一个构造函数,以将“ this”绑定到增量,减量动作创建器函数。像这样:
constructor() {
    super(props)
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
}
  1. 最后,连接到Redux商店,并在AlphaDevs的答案中调度类似的操作