本文介绍了反应:从另一个组件调用setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是父组件:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
news: ""
}
}
componentDidMount() {
this.updateNews();
}
updateNews = () => {
...
}
render() {
<CustomButton type="primary" />
}
这是CustomButton
:
const CustomButton = (props) => {
const {
type
} = props;
const updateItem = () => {
... // The firing of the setState should be here
}
return (
<Button
type={type}
onClick={() => {
updateItem();
}}
>{value}
</Button>
);
如何从CustomButton
中的const updateItem = () => {
内部触发,以便Parent
运行updateNews
或componentDidMount
?
How can I fire from inside const updateItem = () => {
in CustomButton
, so that Parent
runs updateNews
or componentDidMount
?
推荐答案
像这样在父组件中使用componentDidUpdate.
Use the componentDidUpdate in Parent component like this.
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
news: "",
fetchToggle:true
}
}
componentDidMount() {
this.updateNews();
}
componentDidUpdate(prevprops,prevstate){
if(prevstate.fetchToggle!==this.state.fetchToggle){
this.updateNews();
}
}
updateNews = () => {
...
}
fetchToggle=()=>{
this.setState({
fetchToggle:!this.state.fetchToggle;
})
}
render() {
<CustomButton type="primary" fetchToggle={this.fetchToggle} />
}
在子组件中单击按钮,调用此切换功能.
In the child component clicking on button call this toggle function.
const CustomButton = (props) => {
const {
type
} = props;
const updateItem = () => {
... // The firing of the setState should be here
}
return (
<Button
type={type}
onClick={() => {
props.fetchToggle()
}}
>{value}
</Button>
);
请记住,状态切换值是每次单击时更新或获取最新数据的一种简洁,优雅的方法.
Remember that a toggling value in state is a cleaner and elegant way to update or fetch latest data on every click.
这篇关于反应:从另一个组件调用setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!