簡體   English   中英

React:為什么我的子組件會更新其父組件的狀態?

[英]React: Why is my child component updating the state of its parent?

我只是制作一個簡單的表單組件,該組件讀取用戶信息並將其顯示為值形式的表單。 編輯后,更改可以保存或取消。 但是本地狀態更新了它的父狀態,這讓我抓狂了。

我有一個父組件,其狀態對象內有一個用戶信息對象:

 usrInfo: {
    userName: {name: 'usrname', title: "User Name", value: 'state.user'}, 
    firstName: {name: 'fname', title: "First Name", value: "asdf"},  
    lastName: {name: 'lname',  title: "Last Name", value: "asdf"}, 
    title: {name: 'title', title: "Title", value: "asdf" }, 
    email: {name: 'email',title: "E-mail",value: "asdf@asdf.com"}
  },

我的孩子組件顯示此狀態沒問題。 在子級中單擊一個編輯按鈕,並在子級中也調用一個函數,以將userCashe子級狀態設置為其上級用戶狀態:

  casheState() {;
    this.setState((prevState, props) => { 
        return {userInfoCashe: props.user };
    })
  }

然后使用userInfoCash作為值填充表單,並在編輯表單時更新子狀態:

  changeHandler = (event) => {
    let usrCopy = {...this.state.userInfoCashe};
    usrCopy[event.target.id].value = event.target.value;
    this.setState({userInfoCashe: usrCopy});

    console.log(this.state.userInfoCashe[event.target.id].value)
    console.log(this.props.user[event.target.id].value)
            // ^^ these are the same, why?
  };

此功能會更改其父用戶狀態。 為什么會這樣?為什么? 我認為反應是建立在單向數據綁定上的。

謝謝!

this.setState不會立即更新狀態。 異步 因此,如果您的console.log在之前和之后顯示相同的狀態,則僅是因為這個。 您可以嘗試執行以下操作:

this.setState({userInfoCashe: usrCopy}, ()=> {console.log(this.state.userInfoCashe);})

真正查看您的狀態是否發生了變異。 希望這可以幫助。

首先,我建議使用lodash npm,它將支持javascript函數

參考鏈接: https : //www.npmjs.com/package/lodash

安裝lodash:npm install --save lodash

安裝后,將其導入您要使用的文件中

    import _ from "lodash";


    changeHandler = (event) => {
    let usrCopy = _.cloneDeep(...this.state.userInfoCashe);

    usrCopy[event.target.id].value = event.target.value;
    this.setState({userInfoCashe: usrCopy});

    console.log(this.state.userInfoCashe[event.target.id].value)
    console.log(this.props.user[event.target.id].value)
            // ^^ these are the same, why?
  };

請嘗試此操作,它不會更新您的原始狀態,只會更新狀態副本所在的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM