更新道具后如何更新组件

时间:2019-10-15 20:05:18

标签: javascript reactjs redux

更新道具后如何更新组件? 我具有以下组件结构:

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是一个ComponentsRow的表,当单击该行时,会打开ComponentBoard窗口,其中也有一个componentRow。

问题:如何从componentBoard更新componentList中显示的数据?他们有1家商店的类似道具

2 个答案:

答案 0 :(得分:2)

props序列化为初始状态时,您应该监听props中的更改并相应地更新state。在基于类的组件中,您可以在功能组件中使用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
    }
}

答案 1 :(得分:2)

为了更好地了解React,建议您阅读 React Life Cycle

通常的想法是使您的列表进入MyList.js的状态,这样,您就可以通过Mylist.js中的函数对其进行更新,并将其作为道具传递给ComponentBoard。现在,您可以更改MyList的状态,并在更改状态时更改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
}