【问题标题】:Using react-router to redirect upon form submission使用 react-router 在表单提交时重定向
【发布时间】:2021-02-28 18:22:27
【问题描述】:

当我输入搜索词(姓名、电子邮件、用户名)时,我希望页面根据搜索值从所有卡片中过滤出一张卡片。我想当用户按下回车键时,我们需要重定向到一个新页面来显示卡片。

我有搜索栏的代码和负责显示单个用户卡的用户组件。我们是否需要使用 react-router 的 Redirect 功能来实现这一点?我一直在为如何实现它而苦苦挣扎,因为道具(searchItem)也需要传递给用户组件。

搜索栏.jsx

import React, { useState } from "react";
import UserList from "./UserList";
import User from "./Components/User";
import { Link, Redirect } from "react-router-dom";

const SearchBar = () => {
  const [searchItem, setSearchItem] = useState("");

  const handleChange = (e) => {
    console.log(e.target.value);
    setSearchItem(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setSearchItem("");
  };

  return (
    <>
      <div className="searchbar">
        <form onSubmit={handleSubmit}>
          <input
            name="name"
            placeholder="Enter Name, Email or Username to Search"
            type="text"
            className="search"
            value={searchItem}
            onChange={handleChange}
          />
        </form>
      </div>
      <UserList />
    </>
  );
};

export default SearchBar;

用户.jsx

import React from "react";
import Card from "./Card";

const User = (props) => {
  return (
    <Card
      key={props.id}
      name={props.name}
      email={props.email}
      website={props.website}
      phone={props.phone}
    />
  );
};

export default User;

用户列表.jsx

import React, { useState, useEffect } from "react";
import Card from "./Components/Card";

const UserList = ({ searchItem }) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);

        const newData = json.map((object) => ({
          id: object.id,
          email: object.email,
          website: object.website,
          phone: object.phone,
          name: object.name,
        }));

        // previousData is an empty array and the newData consists of all the users
        // using the spread operator, we copy the newData into the previousData
        setData((previousData) => [...previousData, ...newData]);
      });
  }, []);

  return (
    <>
      <div className="container">
        {data.map((info) => {
          return (
            <Card
              key={info.id}
              name={info.name}
              email={info.email}
              website={info.website}
              phone={info.phone}
            />
          );
        })}
      </div>
    </>
  );
};

export default UserList;

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    我认为你不需要在这里使用 react-router 来实现这一点。

    您想要的搜索类型决定了您可以采取的方法。您希望在每次按键时过滤卡片还是仅在表单提交时过滤?

    目前您可以混合使用这两种方法,因为您有一个带有 onSubmitform 元素,但您也有一个带有 onChangeinput 元素(不受控制和受控制)。

    以下是实时搜索、受控组件方法的简化示例:

    const User = (props) => {
      return <p>{props.name}</p>;
    };
    
    const UserList = ({ searchItem }) => {
      const [data, setData] = useState([]);
    
      useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then((response) => response.json())
          .then((json) => {
            console.log(json);
    
            const newData = json.map((object) => ({
              id: object.id,
              email: object.email,
              website: object.website,
              phone: object.phone,
              name: object.name,
            }));
    
            setData(newData);
          });
      }, []);
    
      const filteredUsers = data.filter((user) => {
        return user.name.includes(searchItem);
      });
    
      return filteredUsers.map((user) => {
        return <User key={user.id} name={user.name} />;
      });
    };
    
    const SearchBar = () => {
      const [searchItem, setSearchItem] = useState("");
    
      const handleChange = (e) => {
        console.log(e.target.value);
        setSearchItem(e.target.value);
      };
    
      return (
        <>
          <div className="searchbar">
            <form onSubmit={(e) => e.preventDefault()}>
              <input
                name="name"
                placeholder="Enter Name, Email or Username to Search"
                type="text"
                className="search"
                value={searchItem}
                onChange={handleChange}
              />
            </form>
          </div>
          <UserList searchItem={searchItem} />
        </>
      );
    };
    

    对于不受控制的方法,过滤器的想法可以保持不变,但是您删除input 上的valueonChange 属性并使用您的handleSubmit 函数来设置searchItem。要获取输入的值,您需要使用这种方法使用 ref。请参阅this 了解更多信息。

    sandbox example

    【讨论】:

    • 感谢您的回复!对于用户列表组件,我实际上是从 API 获取数据以显示所有用户。所以我对如何修改它以包含搜索功能有点困惑?我已经使用 UserList 组件编辑了上面的帖子。
    • @TanDev 我已经更新了答案中的代码以显示如何操作。它并没有真正改变方法,您只是过滤从 fetch 接收到的数据。
    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多