父组件更改时更新子组件

我是React js的新手。 我有两个问题。 我来啦

问题1

我想在更新(重新渲染)父组件时更新(重新渲染)子组件。 经过一些谷歌搜索,我发现当道具被更改并且我们调用forceUpdate函数时,只更新父组件而不是子组件。 如果我想更新子组件,我需要使用setState函数并在状态中设置一些东西来更新子组件。 但我面临的问题是,当我在父组件中设置状态时,子组件不会更新。 不调用子项的render方法。 有人可以告诉我,我做错了什么?

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调用到我的后端服务器,当它返回它时更新道具并设置状态,以便该子组件也被重新呈现,但子组件不是重新渲染。 有人可以告诉我出了什么问题。

问题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调用返回的数据,我在应用程序组件中设置了一些道具,我也想要组件二重新渲染,一旦在应用程序中更改了一些道具,有任何方法可以做到这一点

谢谢任何帮助将不胜感激

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

你不能分配道具。 道具从父母传递。 将用户设置为状态并将状态传递给子组件,如下所示:

  

在您的子组件中,您现在可以访问this.props.user 。 此外,不需要this.forceUpdate()。

Interesting Posts