You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用getDerivedStateFromProps后render值未更新求助

问题解决:React类组件中getDerivedStateFromProps未更新render状态

你的代码核心问题是getDerivedStateFromProps方法没有声明为静态方法,React不会调用非静态的该生命周期方法,因此state不会被更新。

修复后的代码

class Strick_ extends React.Component {
  constructor(props) { // 传入props并传给super,避免潜在的props获取问题
    super(props);
    this.state = {
      Name: "",
      Room: "",
      Fair: 0
    };
  }

  // 必须添加static关键字,React才会识别这个生命周期方法
  static getDerivedStateFromProps(props, state) {
    return {
      Name: props.Names
    };
  }

  render() {
    return (
      <>
        <h3>PG Details </h3>
        <p>Room Person:{this.state.Name}</p>
        <p>Room number:{this.state.Room}</p>
        <p>Room fair:{this.state.Fair}</p> {/* 修正拼写错误faie→fair */}
      </>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Strick_ Names="Ankit Chauhan"/>);

额外注意事项

  • getDerivedStateFromProps是React类组件的静态生命周期方法,必须用static修饰,它接收最新的props和当前state作为参数,返回的对象会合并到组件state中。
  • 若你使用React 16.8+版本,更推荐用函数组件结合useState和useEffect实现相同逻辑,代码更简洁易维护:
function Strick_(props) {
  const [state, setState] = React.useState({
    Name: props.Names,
    Room: "",
    Fair: 0
  });

  // 当props.Names变化时更新state.Name
  React.useEffect(() => {
    setState(prev => ({ ...prev, Name: props.Names }));
  }, [props.Names]);

  return (
    <>
      <h3>PG Details </h3>
      <p>Room Person:{state.Name}</p>
      <p>Room number:{state.Room}</p>
      <p>Room fair:{state.Fair}</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Strick_ Names="Ankit Chauhan"/>);
  • 尽量避免过度使用getDerivedStateFromProps,它容易让组件逻辑变得复杂晦涩。如果只是需要根据props同步状态,优先考虑受控组件模式或函数组件的hooks方案。

内容的提问来源于stack exchange,提问作者ankit chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:24:19