axios 无法解析状态元素反应

axios cannot resolve state element react

我对反应和遵循教程还很陌生。讲师正在使用 axios 从 github api 中提取一些数据。以下是他建议的 onSubmit 事件处理程序:

handleSubmit = (event) => {
    event.preventDefault();
  console.log('event: form submit ' + this.state.userName )
  axios.get('https://api.github.com/users/${this.state.userName}')
    .then(resp => {
        console.log(resp)
    });

}

但是,当我 运行 它时,this.state.userName 没有得到解决,我收到 404。代码有问题还是 axios 更新了?我正在使用 jscomplete/repl playground 来处理它。

感谢帮助!

组件代码如下:

class Form extends React.Component {

    state = {
userName: '  ',
event: ' '
}

handleSubmit = (event) => {
    event.preventDefault();
  console.log('event: form submit ' + this.state.userName )
  axios.get('https://api.github.com/users/${this.state.userName}')
    .then(resp => {
        this.setState({event: resp})
    });
  console.log(event)
}

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <input type="text"
                    value={this.state.userName}
        onChange={(event) => this.setState({userName: event.target.value})}
                    placeholder={ this.state.username } required 
      />
      <button>Add Card</button>
    </form>
  )
}
}

您没有按应有的方式使用 ES6 Template literals
在这一行中,您用 ':
包裹了字符串 'https://api.github.com/users/${this.state.userName}'

用反引号 (`) 包裹它(使用波形符按钮)

你真的应该使用构造函数来初始化状态变量。使用反引号(`) 替换字符串中的变量。还将函数绑定到 class 以使用 this 上下文。试试下面的代码

class Form extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            userName: '  ',
            event: ' '
        }

        this.handleSubmit = this.handleSubmit.bind(this)
    }

    handleSubmit = (event) => {
        event.preventDefault();
        console.log('event: form submit ' + this.state.userName)
        axios.get(`https://api.github.com/users/${this.state.userName}`)
            .then(resp => {
                this.setState({ event: resp })
            });
        console.log(event)
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text"
                    value={this.state.userName}
                    onChange={(event) => this.setState({ userName: event.target.value })}
                    placeholder={this.state.username} required
                />
                <button>Add Card</button>
            </form>
        )
    }
}