Ошибка типа в React Native + Redux + Typescript - PullRequest
0 голосов
/ 21 апреля 2020

Привет. Я пытаюсь создать простой пример счетчика редуксов в React native с использованием машинописи, используя этот документ. https://enappd.com/blog/redux-in-react-native-app/92/ Несмотря на то, что в документе используется javascript Я пытаюсь перенести код в Typescript. но я получаю ошибки. вот мой код PS Типовой код машинного кода для реагирования на нативный язык был создан с помощью шаблона Typescript, используемого в официальных документах RN

Counts.ts

import {COUNTER_CHANGE} from '../constants';

export function changeCount(count: number) {
  return {
    type: COUNTER_CHANGE,
    payload: count,
  };
}

CountReducer.ts

import {COUNTER_CHANGE} from '../constants';
const initialState = {
  count: 0,
};
const countReducer = (state = initialState, action: any) => {
  switch (action.type) {
    case COUNTER_CHANGE:
      return {
        ...state,
        count: action.payload,
      };
    default:
      return state;
  }
};
export default countReducer;

App. tsx

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {StyleSheet, View, Button, Text} from 'react-native';
import {connect} from 'react-redux';
import {changeCount} from './actions/counts';
import {bindActionCreators} from 'redux';

interface IRecipeProps {
  count: number;
  actions: any;
}

interface IRecipeState {}

class App extends Component<any, any> {
  decrementCount() {
    let {count, actions} = this.props;
    count--;
    actions.changeCount(count);
  }
  incrementCount() {
    let {count, actions} = this.props;
    count++;
    actions.changeCount(count);
  }
  render() {
    const {count} = this.props;
    return (
      <View style={styles.container}>
        <Button title="increment" onPress={() => this.incrementCount()} />
        <Text>{count.toString()}</Text>
        <Button title="decrement" onPress={() => this.decrementCount()} />
      </View>
    );
  }
}

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

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

const ActionCreators = Object.assign({}, changeCount);
const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(ActionCreators, dispatch),
});

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

index. js

import {AppRegistry} from 'react-native';
import React from 'react';
import App from './App';
import {name as appName} from './app.json';
import {Provider} from 'react-redux';

import configureStore from './configureStore';

const store = configureStore();

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

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

ConfigureStore

import {createStore, combineReducers} from 'redux';
import countReducer from './reducers/countReducer';
const rootReducer = combineReducers({count: countReducer});
const configureStore = () => {
  return createStore(rootReducer);
};
export default configureStore;

Package. json

{
  "name": "ReduxExample",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx"
  },
  "dependencies": {
    "@types/react-redux": "^7.1.7",
    "@types/redux": "^3.6.0",
    "react": "16.11.0",
    "react-native": "0.62.2",
    "react-redux": "^7.2.0",
    "redux": "^4.0.5"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^1.0.0",
    "@types/jest": "^24.0.24",
    "@types/react-native": "^0.62.0",
    "@types/react-test-renderer": "16.9.2",
    "@typescript-eslint/eslint-plugin": "^2.27.0",
    "@typescript-eslint/parser": "^2.27.0",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.58.0",
    "prettier": "^2.0.4",
    "react-test-renderer": "16.11.0",
    "typescript": "^3.8.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

Ошибка Error

1 Ответ

0 голосов
/ 21 апреля 2020

Вы пытаетесь вызвать функцию, как если бы она была свойством объекта actions - actions.changeCount(count) - но вы уже импортировали changeCount явно, поэтому вы можете просто вызвать ее напрямую, например:

incrementCount() {
  let {count, actions} = this.props;
  count++;
  changeCount(count); // not actions.changeCount
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...