【问题标题】:Redux TypeScript can not map state to propsRedux TypeScript 无法将状态映射到道具
【发布时间】:2018-03-26 17:47:09
【问题描述】:

我在 JavaScript 中遵循 redux 教程,但是当我使用 TypeScript 编写时,我无法将状态映射到道具。

App.tsx

import * as React from 'react';
import Todo from '../models/Todo';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import Main from './Main';

export interface State {
  todoList: Todo[];
  filterStatus: string;
  isAdding: boolean;
}

const defaultState: State = {
  todoList: [],
  filterStatus: 'SHOW_ALL',
  isAdding: false,
};

const reducer = (state: State = defaultState, action: {}) => {
  return state;
};

const store = createStore(reducer);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Main />
      </Provider>
    );
  }
}

export default App;

Main.tsx

import * as React from 'react';
import { connect } from 'react-redux';
import { State } from './App';

class Main extends React.Component {
  render() {
    return (
      <div style={{ backgroundColor: 'red' }}>{this.props.filterStatus}</div>
    );
  }
}

function mapStateToProps(state: State) {
  return {
    filterStatus: state.filterStatus,
  };
}

export default connect(mapStateToProps)(Main);

上面写着:

[ts] 属性“filterStatus”不存在于类型“Readonly & 只读'。

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    您需要为组件指定 props 的类型。

    export interface MainProps {
      filterStatus: string;
    }
    
    class Main extends React.Component<MainProps>
    

    【讨论】:

    • 感谢您的快速回答。这是正确的。顺便说一句,我的 State 界面怎么样,是正确的还是我需要折射?
    • 现在我觉得还可以
    猜你喜欢
    • 2017-11-07
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    相关资源
    最近更新 更多