簡體   English   中英

父狀態更改時,子組件不會更新

[英]Child component does not update when parent state changes

我遇到將道具從父母傳遞到孩子的情況。 父級連接到redux存儲,從子級(使用bindActionCreators),我調度一些操作來更改父級連接到的存儲中的狀態。 現在,當我從子級更改存儲中的狀態時,父級會更新,而子級不會更新。 導致更改的(邏輯)/(用戶操作)起源於孩子。 通過從父項本身調度操作並通過回調將子項中的必要信息發送給父項,我解決了這個問題。 現在,父母和孩子都更新。 代碼太大,無法在此處發布,我至少已經使代碼可以工作了。 我只是想知道為什么在孩子派發動作的情況下孩子不更新,有人可以指出我是否在這里遺漏了一些基本概念,或者可能是更復雜的事情,只能通過進入詳細的代碼。

(編輯后包含簡化的代碼)。 此版本是子級分派操作以修改商店的版本,父級會更新,而子級則不會。 如果我將分派移至父級本身,則子級將開始更新。

上級:

class Table extends Component {
render() {
return (
  <div className = 'table-container'>
      {
      this.props.columns.map((column) => 
       <div key = {i}>
         {column}
       </div>
      }
      <TableHeader
      columns = {this.props.columns}
      />
  </div>
  )
 }
}

function mapStateToProps(state){
  return {
    columns: state.columns,
  };
}

export default connect(mapStateToProps, null)(Table);

兒童:

class TableHeader extends Component {

  constructor(props){
    super(props)
    this.getColumnHeadings.bind(this)
  }


  onDragStart(ev, i) {
    ev.preventDefault();
  }

  onDragOver(ev) {
    ev.preventDefault();
  }

  onDrop(ev, i) {
    ev.preventDefault();
    this.props.changeColumns({index: i})
  }


  getColumnHeadings = (columns) => {
    return this.props.columns.map((column, i) =>
        <div key = {i}
        draggable
        onDragStart = {(ev) => this.onDragStart(ev, i)} 
        onDragOver = {this.onDragOver} 
        onDrop = {(ev) => this.onDrop(ev, i)}
        >
        {column}
        </div>
    )
  }


  render() {
    return (
          <div className = 'table-header1'>
            {this.getColumnHeadings(this.props.columns)}
          </div>
    )
  }
}

function matchDispatchToProps(dispatch){
  return bindActionCreators({changeColumns: changeColumns}, dispatch)
}

export default connect(null, matchDispatchToProps)(TableHeader);

動作創建者:

export const changeColumns = (changeInfo) => ({ type: "change columns", payload: changeInfo});

謝謝!

使用connect連接到redux存儲時,需要將狀態傳遞給子組件中的props。

否則您的子組件將不知道狀態已更改(讓redux store通知您的子組件)。

(實際上,如果您通過Table prop將其傳遞給子組件,它確實會這樣做,但是正如您所說的那樣,這不是您想要的,並且沒有必要首先使用Redux。)

function mapStateToProps(state){
  return {
    columns: state.columns,
  };
}

function matchDispatchToProps(dispatch){
  return bindActionCreators({changeColumns: changeColumns}, dispatch)
}

export default connect(mapStateToProps, matchDispatchToProps)(TableHeader);

我認為這樣做的原因可能是,一旦您通過connect HOC將組件連接到Redux Store,您的組件就會根據Redux存儲的更改方式以及觸發mapStateToProps來更新其道具。 似乎當從父級傳遞道具時它不再呈現。 曾經有過這樣的經歷,不得不將道具通過道具的父級組件傳遞。

暫無
暫無

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

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