Javascript 更新道具后如何更新组件
更新道具后如何更新组件? 我有以下组件结构:Javascript 更新道具后如何更新组件,javascript,reactjs,redux,Javascript,Reactjs,Redux,更新道具后如何更新组件? 我有以下组件结构: MyList.js render() { return( <ComponentList products={props.products}> <ComponentBoard product={props.product[i]} //send choosen product(1) from list(100 products) ) } MyList.js render(){ 返回( componentRow也应该更改
MyList.js
render() {
return(
<ComponentList products={props.products}>
<ComponentBoard product={props.product[i]} //send choosen product(1) from list(100 products)
)
}
MyList.js
render(){
返回(
componentRow也应该更改
为了更好地理解:
ComponentList是一个componentRow表,当单击到行时,将打开ComponentBoard窗口,其中还有一个componentRow
问题:如何从componentBoard更新显示在componentList中的数据?在将道具
序列化为初始状态时,它们具有来自1个存储区的类似道具。您应该监听道具
中的更改,并相应地更新状态
。在基于类的组件中,您使用componentDidUpdate
在功能组件中,您可以使用useffect
监听给定prop
const Component = ({ foo }) =>{
const [state, setState] = useState(foo) //initial state
useEffect(() =>{
setState(foo) //everytime foo changes update the state
},[foo])
}
类
等效
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,我建议您阅读
一般的想法是将您的列表设置为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
}
在写问题之前,我尝试了componentDidUpdate,但组件没有更新。我在全局redux存储中更改了“firstname”,在componentBoard名称更改中更改了,但在列表中没有更改
class MyList extends Component {
constructor(){
super();
this.state = {
// an array of objects
}}
handleBoardChange = () => { some function using this.setState }
// the rest of your Mylist class
}