小编典典

使用TypeScript和React-Redux时推断映射的道具

reactjs

我找到了一种使用mapStateToPropsfrom 时获得类型安全性的方法react- redux:如文档所述,您可以定义接口并使用接口进行参数化React.Component<T>

但是,在定义时mapStateToProps,我已经在定义一个函数,可以在该函数中推断结果对象的属性类型。例如,

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

在这里,counter可以推断道具与的类型相同state.counter。但是我仍然必须具有如下的样板代码:

interface AppProps {
    counter: number;
}


class App extends React.Component<AppProps> { ... }

export default connect(mapStateToProps)(App);

所以问题是,有什么方法可以构造代码,从而避免编写counter两次类型的代码?或者避免参数化React.Component-即使我可以从mapStateToProps函数的显式结果类型中推断出组件的属性,那还是更好的选择。我想知道上面的复制是否确实是使用React-
Redux编写类型化组件的正常方法。


阅读 306

收藏
2020-07-22

共1个答案

小编典典

是。还有用于推断组合道具的种类整齐的技术connect将通过基于你的组件mapStatemapDispatch

中提供了一种新ConnectedProps<T>类型@types/[email protected]。您可以像这样使用它:

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

const mapDispatch = {increment};

// Do the first half of the `connect()` call separately, 
// before declaring the component
const connector = connect(mapState, mapDispatch);

// Extract "the type of the props passed down by connect"
type PropsFromRedux = ConnectedProps<typeof connector>
// should be: {counter: number, increment: () => {type: "INCREMENT"}}, etc

// define combined props
type MyComponentProps = PropsFromRedux & PropsFromParent;

// Declare the component with the right props type
class MyComponent extends React.Component<MyComponentProps> {}

// Finish the connect call
export default connector(MyComponent)

请注意,mapDispatch如果它是对象,则typeof mapDispatch可以正确推断出其中包括的重击动作创建者的类型,而事实并非如此。

我们会尽快将其作为推荐的方法添加到官方的React-Redux文档中。

更多细节:

2020-07-22