【问题标题】:React functional components props value not updatingReact 功能组件道具值未更新
【发布时间】:2020-09-15 01:34:17
【问题描述】:

我试图根据父状态简单地呈现 props.item 的值,但它始终显示初始值。但是,在 useEffect 内部,props.item 具有更新的值。如何在不将其保存到 state 的情况下使用更新的 props 值?在基于组件的类中,这将在没有状态的情况下工作。

//编辑:

家长:

function App() {
  const [activePageIndex, setActivePageIndex] = useState(0);
  const changeActivePageIndex = (index) => {    setActivePageIndex(index);
  };

  return (
    <div className="App">
      <div className="app-content">
        <Carousel
          activePageIndex={activePageIndex}
          onScroll={changeActivePageIndex}
        />
      </div>
   </div>
  );
}

export default App;

孩子:

const Carousel = (props) => {
  useEffect(() => {
//Here it shows the updated value

  }, [props.activePageIndex]);
//Here it shows the OUTdated value
  return <div className="carousel-container">{props.activePageIndex}</div>;
};

export default Carousel;

【问题讨论】:

  • 你能告诉我们有这个问题的代码吗?
  • @NicholasTower 你是对的。我刚刚添加了它

标签: javascript reactjs


【解决方案1】:

尝试将setActivePageIndex 直接作为道具传递。

前-

function App() {
  const [activePageIndex, setActivePageIndex] = useState(0);

  return (
    <div className="App">
      <div className="app-content">
        <Carousel
          activePageIndex={activePageIndex}
          onScroll={(e) => setActivePageIndex(e.target.value)}
        />
      </div>
   </div>
  );
}

export default App;

【讨论】:

    【解决方案2】:

    尝试:

    const Carousel = ({activePageIndex}) => {
      useEffect(() => {
    //Here it shows the updated value
    
      }, [activePageIndex]);
    //Here it shows the updated value
      return <div className="carousel-container">{activePageIndex}</div>;
    };
    
    export default Carousel;
    

    【讨论】:

      【解决方案3】:

      你能再多加一点吗,如果你加一点也不花钱:

      • 代码 sn-ps。
      • 预期行为。
      • 实际行为。

      【讨论】:

        猜你喜欢
        • 2020-04-30
        • 2021-02-27
        • 1970-01-01
        • 1970-01-01
        • 2020-11-27
        • 2021-06-15
        • 1970-01-01
        • 2022-11-22
        • 2019-09-16
        相关资源
        最近更新 更多