首页 > 解决方案 > 单个组件中的多个 Redux 状态

问题描述

我想将多个状态合并到一个组件中(我正在起诉 TypeScript)。我注意到这个问题是在 2 年前讨论过的——单个组件中的多个 Redux 状态——Typescript、React、Redux。我尝试了建议的解决方案,但它对我不起作用。还有其他建议吗?

type CompetitorProps =
CompetitorsStore.CompetitorsState // ... state we've requested from the Redux 
store
& StationsStore.StationsState
& typeof CompetitorsStore.actionCreators // ... plus action creators we've 
requested
& RouteComponentProps<any>; // ... plus incoming routing parameters


const Competitors = (props: CompetitorProps) => {

useEffect(() => {
    console.log("In Competitors. useEffect1");
    ensureDataFetched()
}, [])

useEffect(() => {
    console.log("In Competitors. useEffect2");
    ensureDataFetched()
}, [props.selectedStationID])

const ensureDataFetched = () => {
    props.requestCompetitors(props.selectedStationID);
}

return (
    <React.Fragment>
        <h1 id="tabelLabel">Competitors</h1>
        <TableContainer component={Paper}>
            <Table aria-label="simple table">
                <TableHead>
                    <TableRow>
                        <TableCell>Dessert (100g serving)</TableCell>
                        <TableCell align="right">ID</TableCell>
                        <TableCell align="right">Name</TableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                    {props.competitorsArray.map(competitor => (
                        <TableRow key={competitor.nCompetitorId}>
                            <TableCell component="th" scope="row"> 
                              {competitor.stCompetitorName}</TableCell>
                            <TableCell align="right"> 
                              {competitor.nCompetitorId}</TableCell>
                            <TableCell align="right"> 
                              {competitor.stCompetitorName}</TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </TableContainer>
    </React.Fragment>
   );
}

const mapStateToProps = (state: ApplicationState) => ({
competitors: state.competitors,
stations: state.stations
});

export default connect(
(state: ApplicationState) => { ...state.competitors, ...state.stations }, 
CompetitorsStore.actionCreators 
)(withRouter(Competitors as any));

//export default connect(
//    mapStateToProps, 
//    CompetitorsStore.actionCreators 
//)(withRouter(Competitors as any));

标签: reactjstypescriptredux

解决方案


好的,首先保持你的mapStateToProps功能,这样你就可以把你的“合并”集中在那里

connect(mapStateToProps, etc)

根据您所说的要交换

competitors: state.competitors,
stations: state.stations

对于一个属性(您所谓的“合并”)

不知道你为什么要这样做,但基本上你想在一个包含竞争对手和电台的道具上创建一个对象

我从这段代码中得出了这个结论:{ ...state.competitors, ...state.stations }

因此,将您的映射更改为一个属性:

competitorsAndStationsMerged: { ...state.competitors, ...state.stations }

或者你可以做

competitorsAndStationsMerged: { competitors: state.competitors, stations: state.stations }

这是你想要做的吗?


推荐阅读