javascript - 无法访问函数内的 props

标签 javascript reactjs axios

我想在使用 axios 获取数据后访问 props 中的函数,但出现错误:

Expected an assignment or function call and instead saw an expression no-unused-expressions

我可以在 jsx 中访问相同的函数,但是当我尝试从 function/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...
}

关于javascript - 无法访问函数内的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59645114/

相关文章:

javascript - HTML5/javascript 错误

javascript - 将 React 类存储在 JS 变量中

reactjs - base64 编码图像未显示在 Material ui CardMedia 中

javascript - 验证失败时, Backbone 关系验证错误不返回

javascript - ui-router - $state.go() 不工作

javascript - React 变量发生变化,但没有渲染...为什么?

javascript - 将 axios 响应传递给 React 中的子组件

php - 取消Axios请求时如何在Laravel中停止php脚本?

node.js - 如何在express服务器中进行API调用

javascript - 如何在 jquery 中从多个选择器创建对象?