gpt4 book ai didi

reactjs - react : call setState from another component

转载 作者:行者123 更新时间:2023-12-03 13:45:30 29 4
gpt4 key购买 nike

这是父组件:

class Parent extends Component {
constructor(props) {
super(props);
this.state = {
news: ""
}
}
componentDidMount() {
this.updateNews();
}

updateNews = () => {
...
}

render() {
<CustomButton type="primary" />
}

这是自定义按钮:

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 运行 updateNewscomponentDidMount

最佳答案

像这样在父组件中使用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>
);

请记住,状态切换值是一种在每次点击时更新或获取最新数据的更简洁、优雅的方式。

关于reactjs - react : call setState from another component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52983102/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com