java 组件更新_父组件更改时更新子组件

本文探讨了React中父组件更新时子组件未能随之更新的问题,并提供了具体的代码实例。同时,文章还讨论了如何在使用React Router时,实现特定组件在路由变化时的重新渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我对React js有点新意 . 我有两个问题 . 我来啦

Question 1

我想在更新(重新渲染)父组件时更新(重新渲染)子组件 . 经过一些谷歌搜索,我发现当道具被更改并且我们调用forceUpdate函数时,只更新父组件而不是子组件 . 如果我想更新子组件,我需要使用setState函数并在状态中设置一些东西来更新子组件 . But the problem that I'm facing is that when I set state in the parent component the child component is not updated. The render method of the child is not called. Can somebody please tell me what is it that I'm doing wrong?

Parent.jsx

class Application extends React.Component {

isBindEvents=false;

componentWillMount(){

let {dispatch} = this.props;

dispatch(getCompanyInfo( "abcd.com", (res) => { // THIS IS A ACTION CALL

this.props.user = res.data.user;

this.setState({name:res.data.user.name})

this.forceUpdate()

}))

}

render(){

return (

// THIS IS THE CHILD COMPONENT WHICH I WANT TO RE-RENDER WHEN THE PARENT COMPONENT CHANGES

{this.props.posts}

)

}

}

export default connect(mapStateToProps)(Application)

CHILD.JSX

class ABCD extends React.Component {

render() {

let isShowUser = this.props.user

? true

: false;

return (

Here is the user name {isShowUser? this.props.user.name: 'user not present'}

);

}

}

export default connect(mapStateToProps)(ABCD);

现在我正在做的是,当应用程序组件正在挂载时,我生成一个ajax调用到我的后端服务器,当它返回它时更新道具并设置状态,以便该子组件也被重新呈现但子组件不是重新渲染 . 有人可以告诉我出了什么问题 .

Question 2

The next question is related to react router I'm using react router for the routeing.This is how I'm using router

module.exports = {

path: '/',

component: Application,

indexRoute: require('./abcd'),

childRoutes: [

require('./componentTwo'),

require('./componentOne'),

]

};

现在让我们假设我要去组件两个路由,它将呈现组件二,我在应用程序组件中生成一个ajax调用,并根据ajax调用返回的数据,我在应用程序组件中设置了一些道具,我也想要组件二重新渲染一旦在应用程序中更改一些道具有任何方法可以做到这一点

谢谢任何帮助将不胜感激

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值