Redux с использованием ошибки типа ошибки Native React: undefined не является объектом (оценка '_this.props.counter') - PullRequest
1 голос
/ 03 августа 2020

Я пытаюсь использовать redux с react native, следуя примеру в вашем видео-трубе https://www.youtube.com/watch?v=KcC8KZ_Ga2M

Это очень простое приложение-счетчик с минимальным кодированием

Он продолжает выдавать эту ошибку, я пробовал это несколько раз, но не мог понять, что продолжает вызывать ошибку.

«ошибка типа ошибки: undefined не является объектом (оценка '_this. props.counter ') Эта ошибка находится по адресу: в CounterApp (созданном ConnectFunction) "

Это мое приложение. js код ниже

import React, {useState} from 'react';
import { StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import CounterApp from './src/CounterApp'

import {createStore} from 'redux'
import {Provider} from 'react-redux'

const initialState = {
  counter: 0
}

const reducer = (state = initialState, action) => {
  switch(action.type)
  {
    case 'INCREASE_COUNTER':
      return {counter: state.counter+1}
    case 'DECREASE_COUNTER': 
      return {counter: state.counter-1}
  }
  return state 
}

const store = createStore(reducer)

export default function App() {
  return (
    <Provider store={store}>
      <CounterApp/>
    </Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

И мой CounterApp . js код ниже

import React, {useState} from 'react';
import { StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {connect} from 'react-redux'

const CounterApp = () => {
  return (
    <View style={styles.container}>
      <View style={{flexDirection: 'row', width: 200, justifyContent: 'space-around'}}>
        <TouchableOpacity onPress={()=>this.props.increaseCounter()}>
          <Text>Increase</Text>
        </TouchableOpacity>
        <Text>{this.props.counter}</Text>
        <TouchableOpacity onPress={()=>this.props.decreaseCounter()}>
          <Text>Decrease</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

function mapStateToProps(state){
    return{
        counter: state.counter
    }
}

function mapDispatchToProps(dispatch){
    return{
        increaseCounter : () => dispatch({type: 'INCREASE_COUNTER'}),
        decreaseCounter : () => dispatch({type: 'DECREASE_COUNTER'})
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(CounterApp)

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Помогите, пожалуйста, я борюсь с этим в течение нескольких недель.

1 Ответ

1 голос
/ 03 августа 2020

Вы не можете получить доступ к this вашего функционального компонента, особенно к функции стрелки. Вместо этого props является аргументом вашего CounterApp компонента. Тогда ваш компонент будет выглядеть так:

const CounterApp = (props) => {
  return (
    <View style={styles.container}>
      <View style={{flexDirection: 'row', width: 200, justifyContent: 'space-around'}}>
        <TouchableOpacity onPress={() => props.increaseCounter()}>
          <Text>Increase</Text>
        </TouchableOpacity>
        <Text>{props.counter}</Text>
        <TouchableOpacity onPress={() => props.decreaseCounter()}>
          <Text>Decrease</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
...