ReactJS问题:通过变量渲染子组件时props无法更新
问题分析与解决方案
你遇到的核心问题是把组件实例直接存储在了state中。当teamList更新时,state里的旧组件实例并不会自动更新它的props——因为这个组件是在之前的某个时刻创建的,它的props已经固定了,React不会主动去修改已经实例化的组件的props。
正确的做法:在state中存储页面标识,动态渲染组件
我们应该把当前页面的类型(比如一个字符串标识)存在state里,然后在render方法中根据这个标识动态渲染对应的组件。这样每次组件重新渲染时,都会使用最新的teamList来传递props,自然就能拿到更新后的数据了。
修改后的代码示例
class ManagerTeam extends Component { constructor(props) { super(props); this.showTeamMembros = this.showTeamMembros.bind(this); this.showTeamReport = this.showTeamReport.bind(this); this.showTeamTarefas = this.showTeamTarefas.bind(this); this.showVisaoGeral = this.showVisaoGeral.bind(this); this.state = { // 用字符串标识当前页面,而不是组件实例 currentPage: 'visaoGeral', teamList: props.userTeams.list }; } // 把teamList存在state里,数据变化时触发重新渲染 componentWillReceiveProps(nextProps) { this.setState({ teamList: nextProps.userTeams.list }); } showTeamMembros() { this.setState({ currentPage: 'membros' }); } showTeamReport() { this.setState({ currentPage: 'report' }); } showTeamTarefas() { this.setState({ currentPage: 'tarefas' }); } showVisaoGeral() { this.setState({ currentPage: 'visaoGeral' }); } render() { const { currentPage, teamList } = this.state; // 根据currentPage动态渲染组件,每次render都用最新的teamList let CurrentComponent; switch(currentPage) { case 'visaoGeral': CurrentComponent = <ManagerTeamVisaoGeral teamList={teamList}/>; break; case 'membros': CurrentComponent = <ManagerTeamMembros/>; break; case 'tarefas': CurrentComponent = <ManagerTeamTarefas/>; break; case 'report': CurrentComponent = <ManagerTeamReport/>; break; default: CurrentComponent = <ManagerTeamVisaoGeral teamList={teamList}/>; } return ( <div> <SimpleNavBar user={this.props.user} updateArtifacts={this.props.updateArtifacts} updateManagerTeams={this.props.updateManagerTeams} /> <NavBar navBarTitle='Equipas' menuOptions={['Visão Geral', 'Membros', 'Tarefas', 'Report']} loadOptions={[this.showVisaoGeral, this.showTeamMembros, this.showTeamTarefas, this.showTeamReport]} /> <Sidebar activePage="team" isManager={true}/> {CurrentComponent} </div> ); } }
关键改动说明
- state存储页面标识:不再把组件实例存在state,而是用简单的字符串标记当前页面,这样state的更新更轻量,也符合React的设计理念。
- teamList存入state:把
teamList放到state中,这样当props更新时,通过setState更新teamList会触发组件重新渲染,确保渲染时用的是最新数据。 - render中动态生成组件:每次render都会根据当前的
currentPage和最新的teamList生成组件,这样组件总能拿到最新的props。
这样修改后,当teamList变化时,组件会自动重新渲染对应的页面组件,并且传递最新的teamList作为props,问题就解决了。
内容的提问来源于stack exchange,提问作者Bruno Guedes
相关产品推荐
相关产品推荐

