为什么状态仅在使用React Hooks调用两次后才更新?

时间:2020-07-14 18:10:23

标签: javascript reactjs asynchronous ecmascript-6 react-hooks

我一直想了解为什么直到两次更改文本输入中的值(调用handleChange函数)后状态才会更新。我在这里做什么错了?

import React, {useEffect, useState} from "react";

export default function Typeahead(props){
    const {list}  = props;
    const [colorList] = useState(list.map(element => element.toLowerCase()));
    const [color,setColor] = useState();
    const [showResults, setShowResults]= useState(false);
    const [results,setResults]= useState();

    let handleChange = (e) =>{
        setShowResults(true);
        setColor(e.target.value.toLowerCase());
        const match = (colorList) =>{
            return colorList.startsWith(color,0);
        };
        const matches = colorList.filter(match);
        setResults((matches));

        console.log(results);
        console.log(showResults);
    };

    useEffect(() => {

        //setResults(list.map(elements => elements.toLowerCase()));
    }, [results]);

        return(
            <div>
                <input type= "text" onChange={handleChange}/>
                {showResults ?
                    <div>
                        {results.map((options) => {
                            return (
                                <option key={options} value={options}> {options}</option>
                            )
                        })}
                    </div>
                    : null }
            </div>
        );
}

0 个答案:

没有答案