Updating state with props on React child component

后端 未结 4 818
一向
一向 2021-02-01 01:12

I have a React app, where props from a parent component are passed to a child component and the props then set the state on the child.

After I send an updated value to t

4条回答
  •  臣服心动
    2021-02-01 02:04

    A couple of things. The way you bind the functions on click is unusual to say the least. I would suggest that you either do it on constructor, or use an arrow function instead (this will bind the function to the class automatically).

    export default class Parent extends Component {
    
        constructor (props) {
            super(props);
            this.state = {name: ''} 
        }
    
        handleUpdate = (updatedName) => {
            this.setState({name: updatedName})
        }
    
        render () {
            return 
        }
    }
    
    export default class Child extends React.Component {
      constructor(props) {
        super(props);
        this.state = { name: "" };
      }
    
      componentDidMount() {
        this.setState({ name: this.props.name });
      }
    
      handleChange = (e) => {
        this.setState({ name: e.target.value });
      }
    
      handleUpdate() {
        // ajax call that updates database with updated name and then on success calls onUpdate(updatedName)
      }
    
      render() {
        console.log(this.props.name); // after update, this logs the updated name
        console.log(this.state.name); // after update, this logs the initial name until I refresh the brower
        return (
          
    {this.state.name}
    ); } }

    Furthermore, I would suggest you to decide whether the props need to be managed/updated from Parent or Child. Should Parent be responsible for handling state, then you should propagate the handleUpdate to the Parent:

    //@Parent component
     this.handleUpdate} .../>
    
    //@Child component
    handleUpdate = () => {
       this.props.handleUpdate
    }
    

    You shouldn't be required to use any other function (in React 16+) for managing props from child to parent and vice versa.

    Usually these "bidirectional" cases are structure "smells" and signify that the separation of concerns for each component has been misadjusted or has not been fully figured out yet.

提交回复
热议问题