【问题标题】:Correct way to pass arguments to reducer in React+Redux?在 React+Redux 中将参数传递给减速器的正确方法?
【发布时间】:2017-08-26 13:29:49
【问题描述】:

似乎有很多错误的方法可以做到这一点,我相当肯定我正在尝试以错误的方式做到这一点(注意此代码目前不起作用):

class SubmitLink extends React.Component<SubmitLinkProps, {}>{
    constructor(props: SubmitLinkProps) {
        super(props);

        this.urlToPass = "nothing";
    }

    urlToPass: string;
    handleChange(e: React.FormEvent<HTMLInputElement>) {
        this.urlToPass = e.currentTarget.value;
    }

    public render() {
        return <div>
            <div>hello world {this.props.url}</div>
            <input onChange={this.handleChange} type='text'></input>
            <button onClick={() => {
                this.props.submitlink(this.urlToPass);
            }}>submit</button>
        </div>
    }
}

除了代码不起作用(urlToPass 在运行时未定义,不确定原因)这一事实之外,为了从文本字段中获取输入,它看起来需要大量工作。同时,这是我在谷歌上搜索到的唯一方法,但它确实感觉不正确。

【问题讨论】:

    标签: reactjs typescript react-redux


    【解决方案1】:

    这里的问题是元素包含自己的状态,而 React 组件也有自己的内部状态。处理这个问题的最好方法是让 React 组件状态成为事实的来源。您可以在此处阅读有关此最佳实践的更多信息:https://facebook.github.io/react/docs/forms.html

    在您的情况下,应该执行以下操作:

    class SubmitLink extends React.Component<SubmitLinkProps, {}>{
        constructor(props: SubmitLinkProps) {
            super(props);
    
            this.state = { urlToPass: '' }
            this.handleChange = this.handleChange.bind(this)
        }
    
        handleChange(e: React.FormEvent<HTMLInputElement>) {
            this.setState({urlToPass: e.currentTarget.value});
        }
    
        public render() {
            return <div>
                <div>hello world {this.props.url}</div>
                <input value={this.state.urlToPass} onChange={this.handleChange} type='text'></input>
                <button onClick={() => {
                    this.props.submitlink(this.state.urlToPass);
                }}>submit</button>
            </div>
        }
    }
    

    【讨论】:

    • 另外值得注意的是,使用 ES6 语法会自动将 'this' 绑定到函数:myFunction = (params) => { code };
    • 亚当大喊大叫!
    • hmm 尝试该代码我收到此错误:TS2339: Property 'urlToPass' does not exist on type 'Readonly'.
    • 我刚刚修复了代码。这是因为我有this.urlToPass 而不是this.state.urlToPass 作为submitLink 的输入
    • 其实我也试过了,同样的错误,不知道怎么回事。似乎在语法上是有意义的。
    【解决方案2】:

    您应该在构造函数中绑定handleChange 方法。 this.handleChange = this.handleChange.bind(this);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2016-03-01
      • 2017-07-01
      • 1970-01-01
      相关资源
      最近更新 更多