【问题标题】:Why is nothing appearing in my React text/input field as I type?为什么在我键入时我的 React 文本/输入字段中没有出现任何内容?
【发布时间】:2020-07-06 12:27:28
【问题描述】:

我正在使用 React 16.13.0。我想构建一个简单的搜索组件,在用户输入时进行搜索。我已经创建了 ./src/components/Search.jsx

import React, { Component } from "react";

export default class Search extends Component {

    constructor(props) {
        super(props);
        this.state = {
            searchTerm: "",
            setSearchTerm: "",
            searchResults: [],
            setSearchResults: []
        }
        this.handleChange = this.handleChange.bind(this);

    }

    handleChange(event) {
        console.log("value:" + event.target.value);
        this.state.searchTerm = event.target.value;
        fetch('/coops/?contains=' + encodeURIComponent(this.state.searchTerm),{
            method: "GET",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        }).then(response => {
            this.state.searchResults = response;
        });
    }

    render() {
        return (
            <div className="searchForm">
                <input
                    type="text"
                    placeholder="Search"
                    value={this.state.searchTerm}
                    onChange={this.handleChange}
                />
                <ul>
                    {this.state.searchResults.map(item => (
                    <li>{item}</li>
                    ))}
                </ul>
            </div>
        );
    }
}

我遇到的问题是在渲染组件之后,当我键入时,搜索框中没有任何内容。我确实看到针对端点执行的请求,每个请求都包含我要输入的字母。任何有关如何在我键入时将整个搜索词保留在文本字段中的帮助表示赞赏。

【问题讨论】:

    标签: reactjs forms components


    【解决方案1】:

    替换这个:

    this.state.searchTerm = event.target.value;
    

    用这个:

    this.setState({searchTerm: event.target.value})
    

    然后搜索结果:

    this.setState({searchResults: response})
    

    【讨论】:

    • 感谢@PaulRyan,尽管似乎仍然存在一些问题。例如,仅对我键入的最后一个字符以外的所有内容进行提取。例如,当我键入“daveddi”时,正在完成的获取是针对“ttp://localhost:3000/coops/?contains=davedd”。另外,我从哪里得到回复?响应对象本身不包含我的可迭代项目列表。
    • 啊,是的,在您运行 fetch 时状态不会更新,因此您将获得以前的值。这样做encodeURIComponent(event.target.value)。至于响应问题,你的 fetch 返回的响应对象包含什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2020-08-31
    • 2021-10-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多