In my React application, I have two distinct types of components: presentations and containers. It's roughly after Dan Abromov's "Presentational and Container Components", except I don't use Flux or Redux.
Now, I have the following structure:
UsersContainer
├── UsersListContainer
| └── UsersListView
└── AddUserContainer
The UsersListContainer
is responsible for loading data from some REST API, and if that succeeds, it delegates presenting that data to the UsersListView
.
The AddUserContainer
is responsible for adding a new user, again, by invoking an REST API. Now, when that was successful, I would like the UsersListContainer
to refresh its data.
The best I can think of is this:
class AddUserContainer extends React.Component {
render() {
// Other UI elements omitted for brevity
return (<button onClick={ e => props.onUserAdded() }>Add user</button>);
}
}
class UsersListContainer extends React.Component {
componentWillMount() {
// start fetching data using window.fetch;
// the promise callback will but retrieved data into this.state
}
render() {
return (<table></table>);
}
}
class UsersContainer extends React.Component {
render() {
const forceUpdate = this.setState({ ...this.state, refreshToken: Math.random() });
// Other UI elements omitted for brevity
<UsersListContainer key={ this.state.refreshToken } />
<AddUserContainer onUserAdded={ forceUpdate } />
}
}
But this approach feels like mis-using the key
prop. Is there a better / more elegant way to do this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…