Javascript 反应功能组件道具值未更新
我试图根据父状态简单地呈现Javascript 反应功能组件道具值未更新,javascript,reactjs,Javascript,Reactjs,我试图根据父状态简单地呈现props.item的值,但它总是显示初始值。但是,props.item具有更新的值。如何使用更新的道具值而不将其保存到状态?在基于组件的类中,这在没有状态的情况下是可以工作的 //编辑: 家长: function App() { const [activePageIndex, setActivePageIndex] = useState(0); const changeActivePageIndex = (index) => { setActive
props.item
的值,但它总是显示初始值。但是,props.item
具有更新的值。如何使用更新的道具值而不将其保存到状态?在基于组件的类中,这在没有状态的情况下是可以工作的
//编辑:
家长:
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[activePageIndex,setActivePageIndex]=useState(0);
常量changeActivePageIndex=(索引)=>{setActivePageIndex(索引);
};
返回(
);
}
导出默认应用程序;
儿童:
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;
const Carousel=(道具)=>{
useffect(()=>{
//这里显示更新后的值
},[props.activePageIndex]);
//这里显示的是过时的值
返回{props.activePageIndex};
};
导出默认旋转木马;
请您再添加一个lil,如果您添加一些,则不需要任何费用:
- 代码片段
- 预期的行为
- 实际行为
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;
const Carousel=({activePageIndex})=>{
useffect(()=>{
//这里显示更新后的值
},[activePageIndex]);
//这里显示更新后的值
返回{activePageIndex};
};
导出默认旋转木马;
尝试将setActivePageIndex
直接作为道具传递
前
函数应用程序(){
const[activePageIndex,setActivePageIndex]=useState(0);
返回(
setActivePageIndex(e.target.value)}
/>
);
}
导出默认应用程序;
你能给我们看看有这个问题的代码吗?@NicholasTower你说得对。我刚才加的
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;