reactjs - 单个组件中的多个 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));
解决方案
好的,首先保持你的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 }
这是你想要做的吗?
推荐阅读
- css - bootstrap 4 响应式全屏覆盖菜单
- c# - c# ReadAsJsonAsync in framework 4.5
- angular - Internet Explorer 11 中 MatAccordion 组件的缓慢转换
- php - cURL POST 未提交表单
- python - 如何安装 Python 3.5.5?
- c - 如何使用`strtoul`解析零可能有效的字符串?
- wpf - 用于笔划的 WPF InkCanvas Z-Index
- python-3.x - 如何根据 .CSV 地图重命名文件
- java - 是否有一个 java api 可以将 ipv6 地址 fd00:: 识别为本地/私有?
- string - $d 在 printf 中做了什么?