【问题标题】:React Redux - Get User input value [duplicate]React Redux - 获取用户输入值[重复]
【发布时间】:2018-07-29 23:14:34
【问题描述】:

我想获取用户的输入值,然后在我的 Redux 操作fetchData 中使用它。我想在input.onChange时更改我的组件状态中的一个变量,然后从中获取字符串以使用参数调用我的方法。

我在handleChange 上发现了一个错误this is undefined

import React, { Component } from 'react';
import { connect } from "react-redux";
import { fetchData } from "../actions/fetchData";

class SearchBar extends Component {

    constructor() {
        super()

        this.state = {
            tags: ''
        }
    }

    buttonClicked() {
        this.props.fetchData(this.state.tag)
    }

    handleChange(e) {
        this.setState({ tags: e.target.value })
    }

    render() {
        return (
            <section className="section">
                <div className="columns">
                    <div className="column is-half is-offset-one-quarter">
                        <div className="field has-addons">
                            <div className="control is-expanded">
                                <input className="input" type="text" placeholder="dog" onChange={this.handleChange}/>
                            </div>
                            <div className="control">
                                <a className="button is-info" onClick={this.buttonClicked}>
                                    Random!
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        )
    }
}

export default connect(null, { fetchData })(SearchBar);

我在这里想念什么?

【问题讨论】:

    标签: reactjs input redux


    【解决方案1】:

    您必须将this 绑定到您的函数,试试这个:

    ...
    constructor() {
      super()
    
      this.state = {
          tags: ''
      }
      this.buttonClicked = this.buttonClicked.bind(this);
      this.handleChange = this.handleChange.bind(this);
    }
    ...
    

    另外,看看why do you need to bind this on the constructor

    【讨论】:

    • 好的,我会试试的。但这也是好方法吗?我刚刚看到我可以使用箭头函数来不必编写这段丑陋的代码;)
    • 这并不难看,只是我们这样做的方式。但你是对的,你也可以使用箭头函数,但请记住,你可能不想总是绑定this,这就是为什么在构造函数中绑定很方便。
    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2015-07-30
    • 1970-01-01
    相关资源
    最近更新 更多