reactjs - 根据 Child 组件更新 App 状态
问题描述
在更新我在其中执行请求的组件的状态时,我需要更新父组件 ( App.js ) 的状态。Child
GET
componentDidMount()
我试图将函数setPoints
作为道具传递,但不幸的是这不起作用。
这是我尝试过的:
Child
零件 :
class Child extends Component {
state = {
points: null
}
async componentDidMount() {
try {
const res = await axios.get(url);
const data = res.data;
this.setState({
points: data.points,
})
this.props.setPoints();
} catch (err) {
console.log('child', err);
}
}
render() {
return (
<div>
</div>
);
}
}
父组件 ( App
):
class App extends Component {
state = {
points: '',
}
setPoints() {
this.setState({
...this.state,
points: this.state.points
});
}
shouldComponentUpdate(nextState) {
if (this.state.points !== nextState.points) {
return true;
}
return false;
}
render() {
return (
<div className="App">
<Route exact path="/child" render={() => <Child setPoints={this.setPoints} />} />
</div>
);
}
}
谁能帮我解决这个问题?帮助将不胜感激。
编辑
我尝试了 Joe Clay 写的内容,这很有意义,但我仍然遇到错误。这是我更新的代码:
async componentDidMount() {
try {
const res = await axios.get(url);
const data = res.data;
console.log(data.points);
this.props.setPoints(data.points);
} catch (err) {
console.log('child', err);
}
它确实记录了点的值,但由于某种原因,我得到:“无法读取未定义的属性'点'”。
解决方案
考虑父组件中数据的值。我将通过将道具传递给在父组件中执行 setState 的函数来更改数据的值,从而将值更改为所需的值。
父组件
class Parent extends React.Component{
constructor(props){
super(props);
this.state({
name:''
})
}
handleChange(value){
this.setState({name:value});
}
render(){
return (<Child handleChange={this.handleChange} />)
}
}
将 handleChange 函数作为道具传递给子组件。
子组件
export default class Child extends React.Component{
sendData(false){
this.props.handleChange(hello) //make sure to pass the value in the
argument that you wish to do a setState on in the parent component
}
}
这将在父组件中将 name 的值设置为 hello。
推荐阅读
- c - C中冒泡排序中额外零的问题
- arrays - Ruby - 仅打印哈希数组中重复哈希键的值
- mysql - 如何在mysql中索引动态生成的嵌套JSON列
- html - 在密码输入元素内放置屏蔽/取消屏蔽按钮
- ruby-on-rails - Rails在多对多关系中统一了常量错误
- sql - 在子查询中选择 2 小时之间的最短时间
- mysql - MySQL 如果字段等于 X 则显示为 Y
- android - 如何在多个 LatLong Android 地图之间绘制路线?
- javascript - 使用 CSS 创建平滑的粘性标题过渡
- vb.net - 通过 VB.NET 使用 Rar.exe 压缩文件夹?