【发布时间】:2020-05-02 22:10:16
【问题描述】:
在组件 A 中,我有一个带有搜索过滤器的 btn,单击 btn 后,我会将搜索过滤器中的选定值发送到组件 B,在那里它从 api 获取数据并使用 table 呈现信息。
所以我面临的问题是,在第一次点击 btn 时,所有选定的值都会传递给组件 B,并且数据正在呈现,但是当我在更改搜索过滤器值后第二次点击 btn 时,btn func 不起作用。我还通过在组件 B 中显示日志来检查控制台。我只能看到第一个通话记录,但看不到第二个通话。
我是 React 新手,也很少开发前端。谁能告诉我我在哪里做错了?
组件 A:
class Hook extends React.Component<any ,any > {
constructor(props) {
super(props);
this._onButtonClick = this._onButtonClick.bind(this);
this.state = {
showComponent: false,
};
};
_onButtonClick() {
this.setState({
showComponent: true,
});
}
render() {
const {classes} = this.props;
return (
<div>
<Box border={1} className={classes.root} display="flex" >
<div>
<Button variant="contained" color="primary"
onClick={this._onButtonClick}>
Search
</Button>
</div>
</Box>
{this.state.showComponent ?
<BComponent a = {this.state.dropdown1value} b = {this.state.dropdown2value} c = {this.state.dropdown3value} d = {this.state.dropdown4value}/>
: null }
</div>
);
}
}
组件 B:
class BComponent extends React.Component<any ,any > {
constructor(props) {
super(props);
this.getAPIInfo = this.getAPIInfo.bind(this);
this.state = {
result: { allInfo: [] },
};
}
componentDidMount() {
this.getAPIInfo(this.props.a,this.props.b,this.props.c,this.props.d).then(Response => {this.setState({result: Response })});
this.setState({loaderFlag: true});
}
async getAPIInfo(a, b, c, d) {
let res;
try {
calling API
});
} catch (error) {
console.log("API call error", error);
} this.setState({loaderFlag: false});
return res;
}
render() {
const {classes} = this.props;
if(this.state.loaderFlag) {
return (
<Loader /> );
}
else
return (
Rendering API data through material UI table
);
}
}
export default withStyles(useStyles)(BComponent)
【问题讨论】:
-
您需要从您的 ComponentA 代码中添加更多代码。就像您的状态一样,您的下拉菜单和事件处理程序。
-
this.state.showComponent 仅设置一次,因此在第一次单击后它不起作用。组件 B 不会重新渲染。
-
我可以看到,你把你的一些逻辑放到了 componentDidMount 中,但是这个生命周期方法在组件生命周期中只调用一次,在第一次渲染和 dom 更新之后。所以,当你的 props 发生变化时,你需要重新调用你的 api 函数并再次更新状态。在 react 类组件中更好的地方是 componentDidUpdate 方法。在带有钩子的组件中,有 useEffect 。