gpt4 book ai didi

reactjs - reselect createStructuredSelector 如何在 Typescript 中工作?

转载 作者:搜寻专家 更新时间:2023-10-30 20:39:23 25 4
gpt4 key购买 nike

我正在尝试了解重新选择方法 createStructuredSelector 在 Typescript 中的工作原理。我经常看到这种模式:

export interface SomeProps {
readonly property1: string;
readonly property2: boolean;
readonly property3: number;
}

export interface SomeOwnProps {
readonly property3: number;
}

export const someSelector = createStructuredSelector<
SomeState,
SomeOwnProps,
SomeProps
>({
property1: property1Selector,
property2: property2Selector,
property3: (_, props) => props.property3
});

我不明白尖括号内类型的用途。我认为SomeState是Redux store state,SomeOwnProps是父组件传入的props,SomeProps是所有的props该组件使用。但是 SomeOwnPropsSomeProps 有什么区别,为什么需要两者?为什么不能只使用 SomeProps 因为它还包含 SomeOwnProps 中定义的属性?谢谢!

最佳答案

createStructuredSelector 有两种变体 — 一种采用组件自己的 props,另一种则不采用。如果您想要的选择不依赖于 Prop ,那么选择后者会更容易。

考虑这个稍微做作的例子:

/**
* Data source (Redux store or a single reducer).
*/
interface State {
readonly property1: string;
readonly property2: boolean;
readonly property3: number;
}

/**
* Your component's OwnProps.
*/
interface OwnProps {
index: 1 | 2 | 3;
}

/**
* The interface you want to create.
*/
interface DesiredSelection {
someString: string;
someNumber: number;
};

当您的选择取决于 Prop 时:

const mySelector = createStructuredSelector<State, DesiredSelection>({
someString: state => state.property1,
someNumber: state => state.property3
});

当您的选择确实取决于 Prop 时:

const mySelectorBasedOnProps = createStructuredSelector<State, OwnProps, DesiredSelection>({
someString: state => state.property1,
someNumber: (state, props) =>
(props.index === 1)
? 1
: state.property3
});

需要区分OwnPropsDesiredSelection,因为前者会影响后者。根据您的组件从其父级收到的 Prop ,从 Redux 商店的不同部分选择数据是一种常见的模式。

比较现实的例子:

interface State {
translations: {
au: 'Hello, mate!',
uk: 'Welcome, old chap!'
}
}

interface OwnProps {
country: 'au' | 'uk';
}

interface ConnectedProps {
message: string
};

/**
* These are all props your component will receive.
*/
type Props = OwnProps & ConnectedProps;

const getMessage = createStructuredSelector<State, OwnProps, ConnectedProps>({
message: (state, props) => state.translations[props.country]
});

关于reactjs - reselect createStructuredSelector 如何在 Typescript 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53963645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com