简体   繁体   English

React Router Link 组件在重定向时未呈现

[英]React Router Link component not rendering when redirect

I'm using the material-ui library's component Autocomplete with React flux to create a Search Bar that finds users.我正在使用 material-ui 库的组件Autocomplete with React Flux 创建一个查找用户的搜索栏。

I want every option to be a link to a page with more information of that user.我希望每个选项都是指向包含该用户更多信息的页面的链接。 Currently, it only works the first time I click on an option.目前,它仅在我第一次单击选项时才有效。 Every time after that it changes the URL but the page is not re-rendered.之后每次都会更改 URL 但页面不会重新呈现。

This is the Autocomplete code:这是自动完成代码:

export function SearchBar() {
  const [url, setUrl] = useState("/perfil/");

  const { store, actions } = useContext(Context);

  useEffect(() => {
    actions.search();
  }, [url]);

  const artistas = store.artistas.slice();

  return (
    <Autocomplete
      id="autocomplete"
      freeSolo
      disableClearable
      options={artistas}
      getOptionLabel={(option) => option.nombre + " " + option.apellido}
      renderOption={(option) => (
        <Link
          className="text-black text-decoration-none"
          onClick={() => setUrl(url + option.id)}
          to={`/perfil/${option.id}`}
        >
          {option.nombre} {option.apellido}
        </Link>
      )}
      renderInput={(params) => (
        <TextField
          {...params}
          size="small"
          placeholder="Search for your artist"
          margin="normal"
          variant="outlined"
          InputProps={{ ...params.InputProps, type: "search" }}
        />
      )}
    />
  );
}

This is the page where it is redirected:这是它被重定向的页面:

export const Perfil = () => {
  const { user_id } = useParams();

  return (
    <>
        <About user_id={user_id} />
        <Galeria user_id={user_id} />
    </>
  );
};

The flux action is this:助焊剂作用是这样的:

  search: async () => {
        try {
          const response = await fetch(
            process.env.BACKEND_URL + "/api/artistas"
          );
          const data = await response.json();
          setStore({
            artistas: data,
          });
        } catch (error) {
          console.log("Error loading message from /api/artistas", error);
        }
      }

At last, this is the layout page:最后,这是布局页面:

return (
    <div>
      <BrowserRouter basename={basename}>
        <ScrollToTop>
          <Navbar />
          <Routes>
            <Route element={<Inicio />} path="/" />
            <Route element={<Login />} path="/login" />
            <Route element={<Registro />} path="/registro" />
            <Route element={<Perfil />} path="/perfil/:user_id" />
            <Route element={<Producto />} path="/producto/:theid" />
            <Route
              element={<ConfiguracionUsuario />}
              path="/configuracion/:theid"
            />
            <Route element={<h1> Not found! </h1>} />
          </Routes>{" "}
          <Footer />
        </ScrollToTop>{" "}
      </BrowserRouter>{" "}
    </div>
  );

Link tags work first move to url.链接标签首先移动到 url。 After that onClick logic will start after moved link.之后 onClick 逻辑将在移动链接后启动。 So if you want to use Link tag with onClick then i recommend two ways.因此,如果您想将 Link 标签与 onClick 一起使用,那么我推荐两种方法。

  1. react-router-dom v5 or lower: just don't use 'to' property and just use onClick and in the onClick property you can use useHistory hook inside onClick. react-router-dom v5 或更低版本:只是不要使用 'to' 属性,只使用 onClick 和 onClick 属性中,您可以使用 ZB73CAB20CE55A0033CA6F07A587D08 中的 useHistory 钩子。 You can use under 2. Option here too.您也可以在 2. 选项下使用。
  2. react-router-dom v6 or lower: use 'a' tag with onClick property you can use useNavigate hook inside onClick. react-router-dom v6 或更低版本:使用带有 onClick 属性的“a”标签,您可以在 onClick 中使用 useNavigate 挂钩。

I fixed it.我修好了它。 The problem was in the Galeria component.问题出在 Galeria 组件中。 It took the id by props:它通过道具获取了id:

  useEffect(() => {
    actions.producto_galeria(props.user_id);
  }, []);

But we should have used a stored variable with the ID that changes on every click with a flux action, instead of props.但是我们应该使用一个存储变量,其 ID 在每次点击时都会通过 Flux 动作发生变化,而不是 props。 So now, I get the ID as follows:所以现在,我得到如下 ID:

flux new action:通量新动作:

get_artista_id: (artista_id) => {
    setStore({ artista_id: artista_id });
}

Link new onClick:链接新 onClick:

 <Link
  className="text-black text-decoration-none"
  onClick={() => {
    actions.get_artista_id(option.id);
  }}
  to={`/perfil/${option.id}`}
>
  {option.nombre} {option.apellido}
</Link>

useEffect on Galeria to detect the change on the ID:在 Galeria 上使用Effect 来检测 ID 上的变化:

  useEffect(() => {
    actions.producto_galeria(store.artista_id);
  }, [store.artista_id]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM