繁体   English   中英

React hooks onSubmit 延迟渲染一个周期然后 useEffect 一个

[英]React hooks onSubmit render one cycle late then useEffect one

我正在尝试 append 新的 onSubmit 查询,但它在一个周期后 append 。

所以我搜索了很多东西,他们都说使用另一个 useEffect 然后它就会解决。

我使用另一个 useEffect 并立即打印(我真正想要的)。 但是 getSearch 查询仍然晚于 useEffect 之一。

如何将 getSearch function 放入 useEffect 中?

我也尝试过像 isColor(prop) 这样的 put prop 并将 isColor 放在 useEffect 中,这会导致错误。

感谢帮助!!

应用程序.js

import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSearch } from "@fortawesome/free-solid-svg-icons";
import "./search.css";
import PageTitle from "./component/PageTitle";
import Cloud from "./component/Cloud";
import Loading from "./component/Loading";

//https://api.color.pizza/v1/
//data.colors[0].name

const App = () => {
    const [isLoading, setIsLoading] = useState(false);
    const [colorNames, setColorNames] = useState("");
    // const [search, setSearch] = useState("");
    const [query, setQuery] = useState("");
    const [cloudHex, setCloudHex] = useState("ivory");
    const [shake, setShake] = useState(false);
    // const [clicked, setClicked] = useState(false);

    
    const search = useRef('');

    useEffect(() => {
        getColorLists();
    }, []);

    useEffect(() => {
        console.log("useEffect: ",query)
    },[query])

    const getColorLists = async () => {
        const res = await fetch(`https://api.color.pizza/v1/`);
        const data = await res.json();
        setColorNames(data);
        setIsLoading(true);
    };

    const isColor = (query) => {
        let makeUpper =
        query.search(/\s/) == -1
                ? query.charAt(0).toUpperCase() + query.slice(1)
                : query
                      .split(" ")
                      .map((i) => i.charAt(0).toUpperCase() + i.slice(1))
                      .join(" ");

        for (let i = 0; i < colorNames.colors.length; i++) {
            if (colorNames.colors[i].name == makeUpper) {
                setCloudHex(colorNames.colors[i].hex);
                setShake(false)
                return;
            } else if (i == colorNames.colors.length - 1) {
                setShake(true)
                setTimeout(() => {setShake(false)}, 200)
                return;
            }
        }
    };


    const getSearch = (e) => {
        e.preventDefault();
        setQuery(search.current.value);
        isColor();
        console.log(query)
    };

    return (
        <>
            {!isLoading ? (
                <Loading />
            ) : (
                <div className="App">
                    <div className="app-wrap">
                        <PageTitle />
                        <div className="search-wrap">
                            <form onSubmit={getSearch} className="search-form">
                                <input
                                    className="search-bar"
                                    type="text"
                                    ref={search}
                                />
                                <button type="submit" className="search-button">
                                    <FontAwesomeIcon
                                        icon={faSearch}
                                        className="search"
                                    />
                                </button>
                            </form>
                        </div>
                        <Cloud cloudhex={cloudHex} shake={shake} />
                    </div>
                </div>
            )}
        </>
    );
};

export default App;

Cloud.js

import React, {useEffect} from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCloud } from "@fortawesome/free-solid-svg-icons";
import './cloud.css';

const Cloud = ({cloudhex, shake}) => {
    return (
        <div className={`cloud-wrap ${ shake ? "shake-cloud":''}`}>
            <span className="cloudhexname">{cloudhex}</span>
            <FontAwesomeIcon icon={faCloud} className="cloud" style={{color:`${cloudhex}`}} />
        </div>
    );
};

export default Cloud;

您可以使用 useRef 来保留 function 的参考。

请检查您是否真的需要这样做。

const App = () => {
    
 const search_ref = React.useRef(null);
    
      React.useEffect(()=>{
        const getSearch = (e) => {
            e.preventDefault();
            setQuery(search.current.value);
            isColor();
            console.log(query)
        };
        console.log("Updating search_ref...");
        search_ref.current = getSearch;
      },[]);
    
      return(
        <form onSubmit={() => search_ref.current} className="search-form">
        
      </form>
      );
    }

暂无
暂无

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

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