【发布时间】:2021-08-18 00:48:16
【问题描述】:
快速前言:如果您急于发布新帖子,请继续前进,而不是将其标记为重复,因为我真的需要帮助。抱歉,如果我听起来很苛刻,但我经历过太多次了。
我在将以下组件代码转换为基于函数的代码时遇到了问题。有人可以帮忙吗?
class App extends React.Component {
state = {loadings: [],};
enterLoading = index => {
this.setState(({ loadings }) => {
const newLoadings = [...loadings];
newLoadings[index] = true;
return {loadings: newLoadings,};
});
setTimeout(() => {
this.setState(({ loadings }) => {
const newLoadings = [...loadings];
newLoadings[index] = false;
return {loadings: newLoadings,};
});
}, 6000);
};
render() {
const { loadings } = this.state;
return (
<>
<Button loading={loadings[1]} onClick={() => this.enterLoading(1)}>
Click me!
</Button>
</>
);
}
}
ReactDOM.render(<App />, mountNode);
这是我尝试过的:
const [loadings, setloadings] = useState([]);
useEffect((index) => {
console.log("here");
const newLoadings = [...loadings];
newLoadings[index] = true;
setloadings(newLoadings);
setTimeout(() => {
const newLoadings = [...loadings];
newLoadings[index] = false;
setloadings(newLoadings);
}, 6000);
}, []);
// blah blah blah
<Button loading={loadings[0]} onClick={() => setloadings(0)}>Log in</Button>
基本上我在不同的 convert-class-to-funtion 教程之间跳来跳去,遇到了this thread 中描述的问题。然后我尝试实现我自己的版本——但没有成功。
仅供参考,“这里”已打印在控制台中,并且控制台没有抛出任何错误——按钮只是不会动画。
非常感谢。
【问题讨论】:
标签: reactjs react-hooks react-class-based-component