我正在构建一个应用程序,我从 Nodejs 应用程序中收到“投诉”。然后我将这些投诉作为 Prop 传递给子组件。在子组件中,我将这些 props 设置为在 ComponentDidMount() 中声明。但是 render() 函数首先被调用,因此它不会在屏幕上显示任何内容。状态不会立即设置。请帮忙。我已经挣扎了两天了。
这是父组件
class Complainer extends Component {
state = {
complaints: []
};
async componentDidMount() {
try {
const user = auth.getCurrentUser();
console.log(user);
this.setState({ user });
if (!user || user.role !== 'complainer') this.props.history.replace('/');
} catch (ex) {
window.location = '/login';
}
const { data: complaints } = await getComplaints();
this.setState({ complaints });
}
render() {
const { complaints } = this.state;
return (
<React.Fragment>
<Navbar user={this.state.user} />
<div className="container">
<Switch>
<Route
path="/complainer/view-all"
render={props => (
<AllComplaints complaints={complaints} {...props} />
)}
/>
<Route path="/complainer/new-complaint" component={ComplaintForm} />
<Route path="/complainer/not-found" component={notfound} />
<Showcase user={this.state.user} />
</Switch>
<hr />
</div>
</React.Fragment>
);
}
}
export default Complainer;
这是 child
class AllComplaints extends Component {
state = {
data: {
columns: [
{
label: 'location',
field: 'location',
sort: 'asc',
width: 280
},
{
label: 'Title',
field: 'title',
sort: 'asc',
width: 150
}
],
rows: []
}
};
componentDidMount() {
const { complaints } = this.props;
this.setState({ rows: complaints });
}
render() {
const { data } = this.state;
return (
<React.Fragment>
{data.rows && <MDBDataTable striped bordered small data={data} />}
{!data.rows && <h1>There is no complaints to show</h1>}
</React.Fragment>
);
}
}
export default AllComplaints;
问题是,就像在状态中一样,行是空的。即[]。在 componentDidMount()
中,我将即将到来的 props 设置为这个“AllComplaints”组件的状态。
我想将“props”值设置为“this.state.data.rows”。但这并没有发生。设置需要时间,但首先调用 render()
,因此屏幕上不显示任何内容。
请帮忙。
最佳答案
看来您没有设置 this.state.data.rows
而是设置 this.state.rows
并使用 this.state.data.rows
渲染内部
关于javascript - Prop 从父级传递给子级并将这些 Prop 设置为状态不会立即起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55631932/