所以我要根据DRY规则优化代码。
我有2个请求,2个响应,2个GETS,2个POSTS,
我认为我应该使用循环来改变迭代器的数量,但是语法上却有问题。
这是我从axios获取的信息:
componentDidMount() {
fetch('http://localhost:3001/getcounterEbook1')
.then(response => {
console.log(response);
return response.json();
})
.then(count => {
console.log(count);
console.log(count.count);
this.setState({counterebook1: count.count});
}).catch(err => {
});
fetch('http://localhost:3001/getcounterEbook2')
.then(response => {
console.log(response);
return response.json();
})
.then(count => {
console.log(count);
console.log(count.count);
this.setState({counterebook2: count.count});
}).catch(err => {
});
}
这是handleClick1,2函数:
handleClick1(e) {
console.log("Sending ...")
let data = {
clicked: true,
}
axios.post('http://localhost:3001/counterEbook1', data)
.then( res => {
console.log('ok')
})
.catch( () => {
console.log('Message not sent')
})
}
handleClick2(e) {
console.log("Sending ...")
let data = {
clicked: true,
}
axios.post('http://localhost:3001/counterEbook2', data)
.then( res => {
console.log('ok')
})
.catch( () => {
console.log('Message not sent')
})
}
如何将其转换为循环?
答案 0 :(得分:1)
一种可能性是使用一个对象,将其称为myObject
,然后像这样使用map
:
const myObject = {
'counterebook1' : 'http://localhost:3001/getcounterEbook1',
'counterebook2' : 'http://localhost:3001/getcounterEbook2',
};
class Foo extends Component {
....
for (let [key, url] of Object.entries(myObject)) {
fetch(url)
.then(response => {
console.log(response);
return response.json();
})
.then(count => {
console.log(count);
console.log(count.count);
this.setState({key: count.count});
}).catch(err => {
});
}
...
您可以通过首先检索触发事件的源,然后使用同一对象来合并handleClick
handleClick = (e) => {
console.log("Sending ...")
const url = myObject[e.target.id];
let data = {
clicked: true,
}
axios.post(url, data)
.then( res => {
console.log('ok')
})
.catch( () => {
console.log('Message not sent')
})
}
请注意,我们正在将id prop from
e.target and referencing the key/value pair in
myObject . This means that the element rendered must have the
id`属性设置为myObject中的某个键:
例如:
<button onClick={this.handleClick} id={key}>
`Button for ${key}`
</button>
希望获得帮助!