React functional components props value not updating

北城以北 提交于 2021-02-11 12:27:55

问题


I am trying to simply render the props.item 's value based on parent state but it is always showing the initial value. However, inside useEffect the props.item has the updated value. How can I make use of the updated props values without saving it into state ? In Component based classes this would of worked without state.

//EDIT:

Parent:

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;

Child:

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;

回答1:


could you please add a lil more, it does not cost any money if you add some:

  • code snippets.
  • expected behavior.
  • actual behavior.



回答2:


try:

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:


try passing the setActivePageIndex directly as props.

Ex-

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;


来源:https://stackoverflow.com/questions/62052794/react-functional-components-props-value-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!