【问题标题】:search bar functionality, how to make a variable persist搜索栏功能,如何使变量保持不变
【发布时间】:2020-07-10 17:43:49
【问题描述】:

我正在尝试构建一个用于搜索视频的导航栏。这个想法是提取一组视频标题,并通过使用来自搜索栏的用户输入进行过滤。问题是我无法让 searchItem 持续存在。当重定向到 /search searchItem 不是道具的一部分。有什么建议吗?

import React from "react";
import { Link } from 'react-router-dom';


class SearchBar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            searchItem: ""
        };
        this.update = this.update.bind(this);
        this.handleSearch = this.handleSearch.bind(this);
    }

    update() {
        return e => this.setState({ searchItem: e.currentTarget.value });
    }

    handleSearch() {
        // debugger
        // e.preventDefault();
        console.log(this.state.searchItem)
        console.log(this.state)
        // this.props.location.search = this.searchItem;
    }

    render() {

        return (
            <div className="search-form">
                <form onSubmit={this.handleSearch()}>
                    <input type="text"
                        className="search-input"
                        placeholder="Search videos"
                        value={this.state.searchItem}
                        onChange={this.update()}
                    />
                    <button id="search-button">
                        <Link to="/search"><img id="search-icon" src="https://image.flaticon.com/icons/svg/49/49116.svg" alt="" /></Link>
                    </button>
                </form>
            </div>
        );
    }
}

export default SearchBar;
class Search extends React.Component {

    constructor(props) {
        super(props);
        console.log(this.props)
    }


    componentDidMount() {
        this.props.fetchVideos();
        this.props.fetchUsers();
    };

【问题讨论】:

    标签: javascript html react-redux


    【解决方案1】:

    搜索词通常通过将它们作为参数添加到 URL 中来保留,例如 mysite.com/search?search=foo。您也可以使用本地存储或 cookie,但这些选项会削弱浏览器导航。

    在你的渲染函数中,设置&lt;Link to={``/search?search=${this.state.searchItem}``} ...

    然后,在构造函数中,您可以选择如何从 url 中获取查询参数。库查询字符串有工具来促进这一点,或者你可以像这样How to get the value from the GET parameters? 编写自己的。一旦你有了它,你就可以用它来初始化状态。

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多