【问题标题】:Correct type declaration for mapStateToProps of Redux connect (TypeScript 2)Redux connect (TypeScript 2) 的 mapStateToProps 的正确类型声明
【发布时间】:2017-06-23 11:25:16
【问题描述】:

我有一个 Redux 商店并想连接它。这是我的容器组件的摘录:

interface IProps  {
  states: IAppState;
  actions: IAppProps;
}
// mapping state to the props
const mapStateToProps = ( state: IAppState, ownProps = {} ) => ({
  states: state
});
// mapping actions to the props
const mapDispatchToProps = ( dispatch: Redux.Dispatch<IAppState> ) => ({
  actions: Redux.bindActionCreators( actions, dispatch )
});

// connect store to App
@connect<IAppState, IAppProps, any>(
  mapStateToProps,
  mapDispatchToProps
)
export default class App extends React.Component<IProps, {}> {
//...
}

编译时我收到以下问题:

error TS2345: Argument of type '(state: IAppState, ownProps?: {}) => { states: IAppState; }' is not assignable to parameter of type 'MapStateToPropsParam<IAppState, any>'.
  Type '(state: IAppState, ownProps?: {}) => { states: IAppState; }' is not assignable to type 'MapStateToPropsFactory<IAppState, any>'.
    Type '{ states: IAppState; }' is not assignable to type 'MapStateToProps<IAppState, any>'.
      Type '{ states: IAppState; }' provides no match for the signature '(state: any, ownProps?: any): IAppState'.

我正在使用 @types/react-redux@4.4.44 来公开 MapStateToProps 接口。我会认为我的 mapStateToProps 遇到了这个界面......但是有些地方出了问题。有什么想法吗?

【问题讨论】:

    标签: reactjs react-redux typescript2.0


    【解决方案1】:

    好吧,似乎@types/react-redux 接受mapStateToProps 以返回与接收的完全相同的类型。我希望它在映射过程中为道具修改它,例如{ states: AppStateTree }。相反,我修改了状态树combineReducers({ states: myReducer })。所以这段代码工作正常:

    interface IRootState {
      state: IAppState;
    }
    
    const mapStateToProps = ( state: IRootState ) => state;
    
    const mapDispatchToProps = {
      toggleOpenAddFeed
    };
    
    type IProps = IRootState & typeof mapDispatchToProps;
    
    class App extends React.Component<IProps, {}> {
     render() {
        return (
          <div className="main-wrapper">
             <Mycomponent store={this.props} />
          </div>
        );
      }
    }
    
    export default connect( mapStateToProps, mapDispatchToProps )( App );
    

    【讨论】:

      【解决方案2】:

      ownProps 没有任何类型。你必须给它一个类型。

      const mapStateToProps = ( state: IAppState, ownProps: any = {} )
      

      【讨论】:

      • 谢谢你的想法,但它并没有解决我的问题:(
      • 嗯,这很奇怪。查看异常,TypeScript 似乎不喜欢您定义states 的方式。试着看看那个......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2016-08-17
      相关资源
      最近更新 更多