javascript - react : pass value from parent to child does not work

标签 javascript reactjs

我需要将一个值index从父级传递给子级。父级和子级都需要有修改index的功能。当父进程修改index时,子进程无法获取更新。有什么我可以解决的吗?

父类:

constructor(props) {
    super(props);
    this.state = {
        index: 0
    }
}
        parentFunction(dir) {
            this.setState({
                index: 10
            });
        }
    render() {
      return(
         <Child index={this.state.index}/>
    );}

子类:

constructor(props) {
        super(props);
        this.state = {
            index: this.props.index
        };
    }
childFunction(dir) {
    this.setState({
        index: this.props.index+1     
    });
}
render() {
  return(
     <div>{this.state.index}</div>
);}

最佳答案

您不需要在两个类中都保留更新程序函数。您可以将更新程序函数从父级传递给子级,并让父级处理状态更新。另外,根据构造函数中的 props 设置状态也是一种反模式。您应该直接将 child 中的 prop 用于您的用例。如果您需要从 props 更新子状态,请确保也在 componentWillReceiveProps 中执行此操作,因为 constructor 仅在第一次调用,并且 每次父级重新渲染时的 componentWillReceiveProps

componentWillReceiveProps(newProps) {
        if (newProps.index!== this.props.index) {
            this.setState({
              index:newProps.index
            })
        }
    }

但是你需要的是

父类:

constructor(props) {
    super(props);
    this.state = {
        index: 0
    }
}
        parentFunction(dir) {
            this.setState({
                index: 10
            });
        }
     updaterFunction(dir) {
        this.setState((prevState) => ({
           index: prevState.index+1     
        }));
    }
    render() {
      return(
         <Child updaterFunction={(val) => this.updaterFunction(val)} index={this.state.index}/>
    );}

子类:

updateProps = () => {
    this.props.updaterFunction();
}
render() {
  return(
     <div>{this.props.index}</div>
);}

关于javascript - react : pass value from parent to child does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47049362/

相关文章:

javascript - 使用 react-router-dom 网页上没有显示任何内容

javascript - 如何有选择地为具有两个对象数组的对象设置状态?

asp.net - 请告诉我在以下转换为 float 的 javascript 代码中我在哪里犯了错误

javascript - 函数中的局部变量覆盖在循环中多次运行

javascript - Safari 零高度 SVG 路径不触发鼠标事件

javascript - 无法读取reducer redux中未定义的属性 'data'

reactjs - 如何使用 createAsyncThunk 帮助程序分派(dispatch) AsyncThunk

javascript - 您能否从源代码中显示的属性中检索值?

javascript - 显示为正方形的图标

reactjs - react-router-dom 不会在路由更改时渲染组件