我的问题与其他问题在堆栈溢出方面有些不同,因为我已经在使用Redux,而且我的问题是数据未正确加载。让我解释一下:
我有两个成分Bookings
和Rooms
,它存在于我的Routes
中:
class Routes extends React.Component {
render() {
return (
<Switch>
<Route path='/' exact component={Bookings} />
<Route path='/bookings' component={Bookings} />
<Route path='/rooms' component={Rooms} />
</Switch>
);
}
}
Bookings
的简化版本:
class Bookings extends React.Component {
componentDidMount(){
this.props.load(services['bookings']);
}
render() {
const bookingsList = this.props.bookings.map(booking => <p>Booking ID: {booking.id} Booking: {booking.name} Room ID: {booking.room_id}</p>)
return <>
<p>Bookings are</p>
{bookingsList}
</>
}
}
function mapStateToProps(storeState){
let bookings = storeState.bookingsState;
return { bookings : bookings };
}
function mapDispatchToProps(dispatch){
let actionDispatchers = bindActionCreators(actionCreators, dispatch);
return actionDispatchers;
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Bookings);
Rooms
:
class Rooms extends React.Component {
componentDidMount(){
this.props.load(services['rooms']);
}
render() {
const roomsList = this.props.rooms.map(room => <p>Room ID: {room.id} Name: {room.name}</p>)
return <>
<p>Rooms are:</p>
{roomsList}
</>
}
}
function mapStateToProps(storeState){
let rooms = storeState.roomsState;
return { rooms : rooms };
}
function mapDispatchToProps(dispatch){
let actionDispatchers = bindActionCreators(actionCreators, dispatch);
return actionDispatchers;
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Rooms);
每个组件独立运行都很好。我想在roomsState
中使用Bookings
将“房间ID”解析为“房间名称”。所以我在roomsState
中添加了mapStateToProps
:
function mapStateToProps(storeState){
let bookings = storeState.bookingsState;
let rooms = storeState.roomsState;
return { bookings : bookings, rooms: rooms };
}
但是这里的问题是,我猜想是直到用户导航到roomState
组件,数据才被加载到Rooms
中。
我应该如何以正确的react-redux方法解决它?
答案 0 :(得分:0)
在load
组件中调用Routes
动作,并将其传递给Bookings
,如下所示:
class Routes extends React.Component {
componentDidMount(){
this.props.load(services['rooms']);
}
render() {
return (
<Switch>
<Route
path='/'
render={(props) => <Bookings {...props} rooms={this.props.rooms} />}
/>
<Route
path='/bookings'
render={(props) => <Bookings {...props} rooms={this.props.rooms} />}
/>
<Route
path='/rooms'
render={(props) => <Rooms {...props} isAuthed={true} />}
/>
</Switch>
);
}
}
function mapStateToProps(storeState){
let rooms = storeState.roomsState;
let bookings = storeState.bookingsState;
return { rooms : rooms, bookings: bookings };
}
function mapDispatchToProps(dispatch){
let actionDispatchers = bindActionCreators(actionCreators, dispatch);
return actionDispatchers;
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Routes);