Reactjs: handleNames()函数通过页面加载通过Reactjs axios自动发布数据。
当我点击职位名称按钮时,应该发布每个人的姓名。
但这里是
handleNames()函数似乎会在页面加载时通过axios自动发布数据。
当我检查控制台时,我可以 无需我单击Post-Name按钮,就可以看到通过handleNames()每秒自动对axio API进行的每秒3000次以上的请求/调用。
请对此提出任何解决方案 当我单击“帖子名称”按钮时,才将帖子发布到axios
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [], loading: false
}
this.handleNames = this.handleNames.bind(this);
}
componentDidMount() {
this.setState({
data:
[{"id":"1","name":"Tony","gender":"male"},
{"id":"2","name":"Mark","gender":"male"},
{"id":"3","name":"Joy","gender":"female"}]
});
}
handleNames(name) {
const data1 = {
name: name
};
axios.get("http://localhost/postname.php", {data1})
.then(response => {
this.setState({data: response.data});
console.log(this.state.data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<span>
<label>
<ul>
{this.state.data.map((person, i) => (
<li key={i}>
{person.name} - {person.gender}
<br />
<input type="button" value="Post-Names" onClick={this.handleNames(person.name)} />
</li>
))}
</ul>
</label>
</span>
);
}
}
答案 0 :(得分:0)
您将立即在此处调用处理程序函数:
onClick={this.handleNames(person.name)}
您应该将其与onClick
回调一起使用。
onClick={() => this.handleNames(person.name)}
答案 1 :(得分:0)
在您的输入#!/bin/bash
set +e
# If I write the following:
if ! (rm -rf sim && mkdir sim && cd sim); then
echo $0: Cannot prepare simulation directory
exit 1
fi
# it does not change the current directory
echo $PWD
# Also, if I write the following:
if ! rm -rf sim || ! mkdir sim || ! cd sim; then
echo $0: Cannot prepare simulation directory
exit 1
fi
# it also does not change the current directory
echo $PWD
# In order to change the current directory, I need to write:
rm -rf sim && mkdir sim && cd sim
if [ $? -eq 1 ]; then
echo $0: Cannot prepare simulation directory
exit 1
fi
# Now it prints .../sim
echo $PWD
cd ..
# Is it possible to write it without an additional line with $?
exit
处理程序中,您正在传递和评估函数,这就是它在render上被调用而自动发布的原因。点击处理程序应接收函数,因此您可以尝试执行以下操作:
onClick
或使handleNames方法如下:
<input
type="button"
value="Post-Names"
onClick={() => this.handleNames(person.name)}
/>
希望它能解决问题,欢呼。