gpt4 book ai didi

javascript - onClick 改变子组件 ReactJS 的状态

转载 作者:行者123 更新时间:2023-12-02 22:23:49 24 4
gpt4 key购买 nike

我想更新两个组件之间的状态,我的 react 知识有点生疏,但这就是我构建组件的方式。

子组件 - 向 API 端点发出获取请求,并将数据呈现到我的图表库

    export default class EmployerLearningNeeds extends Component {
constructor(props) {
super(props)
this.state = {
employerData: [],
}
}

componentDidMount() {
this.fetchData() //
}

fetchData = () => {
axios.get(fullAPI).then(res => {
const apiResponse = res.data
apiResponse.map(employer => {
console.log('ChildResponse', apiResponse)
// eslint-disable-next-line no-param-reassign
employer.value = employer.value.toFixed(2)
return employer
})
this.setState({
employerData: apiResponse,
})
})

}

getOption = () => ({ data: this.state.employerData })

render() {
return(
<ReactEcharts option={this.getOption()}
)}

父组件 - 渲染我的子组件,单击按钮应该更新我的子组件的状态

export default class InterviewInsights extends Component {
constructor(props) {
super(props)
this.state = {
employerData: [], }
}

testFunction = () => {
axios.get(apiURL).then(res => {
console.log('Parent response', res.data)
this.setState({
employerData: res.data,
})
})
}
render() {
return (
<button href="#" onClick={this.testFunction}>
click me
</button>
<EmployerLearningNeeds employerData={this.state.employerData} />
)
}

最佳答案

从父组件传递到子组件的任何内容都将位于 this.props 中,而不是 this.state 中。

从您的代码来看,您似乎希望父级能够获取一组不同的数据并将其传递给子级进行渲染。

如果父级要执行提取操作并向下传递数据,为什么还要在子级中添加 fetchData 呢? (如果我遗漏了一些东西,我很抱歉 - 不能 100% 确定你要做什么。)

(由于 componentWillReceiveProps 现已替换为 static getDerivedStateFromProps)

static getDerivedStateFromProps(props) {
const apiResponse = props.employerData;
apiResponse.map(employer => {
console.log('ChildResponse', apiResponse);

// eslint-disable-next-line no-param-reassign
employer.value = employer.value.toFixed(2);

return employer;
})

return { employerData: apiResponse };
}

只要父级为 employerDetails 传入一组新数据,处理数据并将结果放入 this.state(这意味着您可以保留您的 render() 函数按原样)。


您还可以删除 componentWillMountfetchDatagetOption 并将 render 更改为以下内容:

render() {
const { employerData } = this.props;
const option = employerData.map(e => e.value = e.value.toFixed(2));

return(
<ReactEcharts option={{ data: option }}
)
}

关于javascript - onClick 改变子组件 ReactJS 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59131589/

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