在ComponentDidmount写了一系列方法函数,给函数赋值为var device 现在想在onClick里面调用device里面嵌套的函数signin,但调用不成功
试过在构造函数中绑定device,在onclick箭头函数绑定device但控制台依旧提示ComponentDidmount中的device声明但从未使用。求解,是逻辑有问题还是方法有问题
相关代码
import ...
class App extends Component{
constructor(props){
super(props);
...
}
componentDidMount() {
function appendmsg(info) {
this.setstate.msg += info + "\n";
}
var device = () => {
return {
getUrl: function(type, opts) {
var deviceip = this.state.deviceIp;
var winname = this.state.winName;
var serverip = this.state.serverIp;
var toserver = this.state.toServer;
if (toserver) {
//指令发往服务器中转设备
opts.ip = deviceip;
opts.wn = winname;
return "http://" + serverip + ":27000/Bridge?t=TermCommand";
} else {
//指令直接发给设备
return "http://" + deviceip + ":27100/Terminal?t=" + type;
}
},
getResult: function(data, type, element) {
//查询结果
data = JSON.parse(data);
if (data) {
if (data.idx) {
//如果idx有效则表示结果未返回
//计时,2s后查询
setTimeout(function() {
device.termCommandResult(data.idx, type, element);
}, 2000);
} else if (type === 2) {
element.src = "data:image/jpg;base64," + data.message;
}
}
appendmsg(JSON.stringify(data));
},
signin: function() {
var pno = this.state.pno;
var uno = this.state.uno;
var opts = {
type: "SignIn",
p: pno,
u: uno
};
var url = device.getUrl("SignIn", opts);
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
body: JSON.stringify(opts)
}).then(function(res) {
return res.json().then(data => {
device.getResult(data);
});
});
}
}
render() {
return (
...
<Button type="primary" onClick={(this.device.signin)}>签到</Button>
...
);
}
}
export default App;
这个函数写在componentDidMount里,作用域是componentDidMount这个函数,所以这个device是一个局部变量,你应该写在组件类里面