【问题标题】:When params or queries chnage the component does not update当参数或查询更改时,组件不会更新
【发布时间】:2020-08-22 23:55:36
【问题描述】:

我正在使用 react-router-dom v5,并且 react 16

每当我这样导航时:

从“/products/:someId”到“/products/:someOtherId”

url 发生变化,但组件没有相应更新

查询也是如此。

“/products?search=something”或“/products?search=someOtherThing”

当我在不同的网址中时,它确实有效,例如“/”或“/users”,

我使用 Link 进行导航,我也尝试了 useHistory 钩子:history.push、history.replace 和 withRouter(myComponent);

这就是我从查询/参数中获取数据的方式

async function searchProducts(searchValue) {
  const response = await axios.post(
    "http://localhost:8000/api/products/search",
    { search: searchValue });
  return response.data.body;
}

const useFetchData = (query) => {
  const [products, setProducts] = useState([]);
  useEffect(() => {
    if (products.length === 0) {
      // Use searchProducts for the request
      searchProducts(query).then((foundProducts) => {
        setProducts(foundProducts);
      });
    }
  }, [products, query]);

  return products;
};

然后我 useFetchData 在我的组件中:

const ProductList = () => {
  const history = useHistory();
  // parsing query to be -> { search: "value" }
  const urlQuery = queryString.parse(history.location.search);
  const products = useFetchData(urlQuery.search);

  const getList = () => {
    return products.map((product) => {
      return (
        <li key={product._id}>
          <ProductItem product={product} />
        </li>
      );
    });
  };

  return <div className="container">{getList()}</div>;
};

搜索按钮位于标题的不同组件中,它始终存在,因为它在布局中

<button className="header-search-button" onClick={handleClick}>
  Search
</button>

和handleClick:

// searchvalue has it's own onChange handler 
const [searchValue, setSearchValue] = useState("");

// code...

const handleClick = () => {
    // .... some code

    // I also tried with push and Link 
    history.replace(`/products?search=${searchValue}`);
};

【问题讨论】:

  • 请根据参数发布您如何获取数据的代码
  • 我贴了一些代码

标签: reactjs react-router-dom


【解决方案1】:

没有代码真的很难分辨。 但我猜你可以将 /products?search=bag 更改为 /products?search=watch。 但在那之后它不能更新状态,因此不能重新渲染。当你重新加载时,就会发生渲染。 如果我们能看到代码会更容易。

【讨论】:

  • 您在搜索时不会触发 searchProducts() 函数。但是当您重新加载浏览器时它会被触发。您只是替换 URL 中的值,您还需要触发 api得到回应。你如何调用 searchProducts() 函数?你能解释一下你的组件吗?
  • 当我按“搜索”时,我的 ProductList 组件使用 useFetchData ,它又调用了 searchProducts
  • 您正在使用触发 api 调用的 useEffect()。你的 useEffect 有依赖关系,所以它只会在依赖关系发生变化时触发。看起来当你点击搜索时,这些依赖关系没有改变,因此 useEffect 不会触发。
  • 我的错。我没有包括依赖项,我认为它不会造成任何伤害,加上 products.length === 0 条件也是一个问题,因为我第二次进行搜索我的产品列表不是空的,因此它永远不会调用 searchProducts。谢谢你的帮助:)
猜你喜欢
  • 2018-06-16
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
相关资源
最近更新 更多