gpt4 book ai didi

javascript - 有没有一种方法可以简化 React.js 中状态中的一长串代码

转载 作者:行者123 更新时间:2023-11-29 23:06:15 26 4
gpt4 key购买 nike

我有一个图像 slider {Carousel},它有自己的文本,文本从左右滑入。我通过在间隔内使用 if 语句在状态中添加每个效果来实现这一点,但代码真的很长,必须有一种方法可以用更少的代码来实现。提前谢谢。

状态

  class Showcase extends Component {
constructor(props) {
super(props);
this.state = {};
}

ComponentDidMount

  defaultState() {
const arr = [
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine"
];
const dir = ["Right", "Left"];
const obj = { width: 0 };
for (let i = 0; i < dir.length; i++) {
for (let k = 0; k < arr.length; k++) {
obj[`animate${dir[i]}${arr[k]}`] = "";
}
}
return obj;
}
componentDidMount() {
console.log(this.state);
console.log(this.defaultState());
this.sliderwidth();
this.showAnime();
const wow = new WOW();
wow.init();
}

方法

  showAnime = () => {
const arr = [
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine"
];
let counter = 0;
setInterval(() => {
counter++;
if (counter === 9) {
this.setState(this.defaultState());
} else {
const state = this.state;
state[
`animateLeft${arr[counter]}`
] = `animated fadeInLeftBig delay-${arr[counter].toLowerCase()}`;
state[
`animateRight${arr[counter]}`
] = `animated fadeInRightBig delay-${arr[counter].toLowerCase()}`;
this.setState(state);
}
}, 7000);
console.log(this.state);
};

sliderwidth = () => {
setInterval(() => {
const slide = this.state.width + 100;
this.state.width === 800
? this.setState({
width: 0
})
: this.setState({
width: slide
});
}, 7000);
};

最佳答案

好的,这是代码。简单的想法是创建一个数字数组,如 ['One','Two'...]

创建默认状态的方法

function defaultState(){
const arr = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
const dir = ['Right','Left']
const obj = {width:0}
for(let i = 0;i<dir.length;i++){
for(let k = 0;k<arr.length;k++){
obj[`animate${dir[i]}${arr[k]}`] = '';
}
}
return obj;
}
console.log(defaultState())

showAmine 函数

showAnime = () => {
const arr = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
let counter = 0;
setInterval(() => {
counter++;
if(counter === 9){
this.setState(defaultState());
}
else{
const state = this.state;
state[`animateLeft${arr[counter]}`] = `animated fadeInLeftBig delay-${arr[counter].toLowerCase()}`
state[`animateRight${arr[counter]}`] = `animated fadeInRightBig delay-${arr[counter].toLowerCase()}`
this.setState(state)
}
}, 7000);
};

关于javascript - 有没有一种方法可以简化 React.js 中状态中的一长串代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54706844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com