reactjs - 反应:从另一个组件调用 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>
);
我怎样才能从里面开火const updateItem = () => {
,CustomButton
这样Parent
跑updateNews
还是componentDidMount
?
解决方案
像这样在 Parent 组件中使用 componentDidUpdate。
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} />
}
在子组件中单击按钮调用此切换功能。
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>
);
请记住,状态中的切换值是在每次点击时更新或获取最新数据的更简洁和优雅的方式。
推荐阅读
- excel - 将数据从 excel 复制到现有的 powerpoint 图表
- javascript - 使用 .select jquery 但没有得到任何选定的文本
- javascript - HTML5 直接从 Safari iOS 上的照片库中选择照片
- python - Python中的df_dict
- kivy - 在 RecyleView kivy 中添加 KivyMD 扩展面板
- javascript - Express.Js:从键值为字符串值的对象中获取值
- java - 从特定 URL 下载 pdf 时出现“java.net.SocketException: Connection reset”异常
- c# - 对表达式树的反射:传递参数并访问静态类上的字段,但使用表达式树
- freeswitch - CentOS Freeswitch v1.10:全新安装时没有音频
- go - 没有与本地包的查询“最新”匹配的版本