javascript - 无法访问函数内的道具
问题描述
我想在使用 axios 获取数据后访问 props 中的函数,但出现错误:
期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions
我可以在 jsx 中访问相同的函数,但是当我尝试从函数/axios 调用它时它不起作用。这是我的代码:
function LoginModal(props) {
let emailInput = React.createRef();
let passwordInput = React.createRef();
const getToken = (props) => {
axios.post('http://localhost:8000/api/token/', {
username: emailInput.current.value,
password: passwordInput.current.value
})
.then(function (response) {
props.closeModalHandler();
})
}
return (
<div className={styles.Background} onClick={props.closeModalHandler}>
<div className={styles.ModalContainer}>
<h2>Log in.</h2>
<div className={styles.InputContainer}>
<input type="text" className={styles.Input} ref={emailInput} />
<label htmlFor="" className={styles.ActiveLabel}>Email</label>
</div>
<div className={styles.InputContainer}>
<input type="password" className={styles.Input} ref={passwordInput}/>
<label htmlFor="" className={styles.ActiveLabel}>Password</label>
</div>
<button className={styles.LoginButton}
onClick={getToken}>Log me in</button>
<p>Forgot password? <br/>
Reset it <b>here</b>
</p>
</div>
</div>
)}
解决方案
props
没有传递给onClick
处理程序(合成的 React 事件对象是)。只需从getToken
参数列表中删除参数,使其关闭传递给的参数LoginModal
:
const getToken = () => {
// −−−−−−−−−−−−−−^^
axios.post('http://localhost:8000/api/token/', {
username: emailInput.current.value,
password: passwordInput.current.value
})
.then(function (response) {
props.closeModalHandler();
})
// *** Handle errors here -- you probably have to close the modal even
// when things go wrong...
}
推荐阅读
- java - 连接到多台主机时出现 EclipseLink 异常“连接是只读的”
- html - 使用 br 和 hr 标签后,段落标签属性不起作用
- python - 将具有等于的字典转换为 json 字典
- python - Python - 按值中的第二项对嵌套字典进行排序
- linux - 通过veth对遍历两个不同网络命名空间中的两个进程时,以太网数据包是否保留在linux内核中?
- mongodb - MongoDB auth 在 SPRINGBOOT 中失败,但在 mongo SHELL 中一切正常,为什么?
- javascript - 理解(误解?)JavaScript 中基于原型的类
- python - 如何使用 python 脚本计算系统中可用的网络接口数量?
- kubernetes - 如何在一个入口控制器中实现多项服务?他们在文档中给出的一个是无法理解的
- c# - 桌面应用程序中的 Google 身份验证