簡體   English   中英

更新道具反應后如何更新組件

[英]How to update a component after updating props react

更新道具后如何更新組件? 我有以下組件結構:

MyList.js 
render() {
 return(
  <ComponentList products={props.products}>
  <ComponentBoard product={props.product[i]} //send choosen product(1) from list(100 products)
 )
}

並且下一個組件有 2 個相似的組件 contentRow

ComponentList.js (
same(
 <contentRow > list .map() //100 contentRow
)

ComponentBoard.js
same(
 <contentRow > // 1 contentRow
)

在組件 componentRow 中有顯示的字段,並通過 redux 更改存儲中的數據,例如用戶名。

當我打開 ComponentBoard 組件並更改 ComponentRov 字段中的值時,ComponentList> componentRow 中的值也應該更改。

為了更好地理解:

ComponentList 是一個ComponentRow 的表格,當點擊到行時,打開ComponentBoard window,其中還有一個componentRow。

問題:如何從componentBoard更新componentList中顯示的數據? 他們有來自 1 家商店的類似道具

當將props序列化為初始 state 時,您應該監聽props的變化並相應地更新state 在基於 class 的組件中,您在功能組件中使用componentDidUpdate您可以通過useEffect監聽給定prop的變化來實現相同的結果

const Component = ({ foo }) =>{
    const [state, setState] = useState(foo) //initial state

    useEffect(() =>{
        setState(foo) //everytime foo changes update the state
    },[foo])
}

class等效

class Component extends React.Component{
    state = { foo : this.props.foo } // initial state

    componentDidUpdate(prevProps){
          if(prevProps.foo !== this.props.foo)
              this.setState({ foo : this.props.foo }) //everytime foo changes update the state
    }
}

為了更好地理解 React,我建議你閱讀React Life Cycle

一般的想法是將您的列表放入 MyList.js 的 state 中,這樣,您可以通過 Mylist.js 中的 function 對其進行更新,並將其作為道具傳遞給 ComponentBoard。 現在您可以更改 MyList 的 state 並且當更改時,ComponentList 也會更改。

class MyList extends Component {
constructor(){
super();
this.state = {
// an array of objects 
}}

    handleBoardChange = () => {  some function using this.setState }
// the rest of your Mylist class
}

暫無
暫無

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

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