问题
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