我想通过单击函数更改API参数并呈现新数据。当我通过onclick事件监听器触发componentDidUpdate时,api数据首先发生了变化,并且在第一次点击时运行良好。但当第二次点击时,api调用完全运行。参数currentPage分配给this.state.count
和this this.state.count
,值在单击时递增。
我下面的代码:
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
count: 1,
};
}
componentDidMount() {
this.ProductList();
}
componentDidUpdate() {
let change = document.getElementById("change");
change.addEventListener("click",(e)=>{
this.changeParams();
this.ProductList();
})
}
changeParams = (e) =>{
this.setState({count: this.state.count + 1})
}
ProductList() {
var myHeaders = new Headers();
myHeaders.append("Cookie", "PHPSESSID=822cu5ctftcpo8f98ehklem4k9");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("http://192.168.31.236/magento/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=category_id& searchCriteria[filterGroups][0][filters][0][value]=2& searchCriteria[filterGroups][0][filters][0][conditionType]=eq&searchCriteria[sortOrders][0][field]=price& searchCriteria[sortOrders][0][direction]=ASC& searchCriteria[pageSize]=20& searchCriteria[currentPage]="+this.state.count, requestOptions)
.then(response => response.text())
.then(result => this.setState({products:result}),)
.catch(error => console.log('error', error));
}
render() {
const productsList = () =>{
let pro = [];
if(typeof this.state.products === 'string') {
pro = JSON.parse(this.state.products)
console.log(pro)
}else{
pro = []
}
if(pro.items && typeof pro.items !== "undefined"){
return pro.items.map((item, i) => (
<div>
<h1>{ item.name }</h1>
</div>
));
}
}
return(
<div>
{productsList()}
<button id="change">Change</button>
</div>
);
}
}
export default App;
与其手动附加事件侦听器,不如通过React执行。在大多数情况下,您不应该直接执行DOM操作。
class App extends React.Component {
// ...
/* You don't need this
componentDidUpdate() {
}
*/
handleChangeClick = () => {
this.changeParams();
this.ProductList();
}
// ...
render() {
// ...
return(
<div>
{productsList()}
<button id="change" onClick={this.handleChangeClick}>Change</button>
</div>
);
}
}
您的方法不起作用的原因是React可能以您意想不到的方式生成和销毁DOM元素,因此确保手动将事件侦听器附加和分离到正确的元素是很难做到的。