条件渲染的反应状态设置时间

React state setting timing for conditional rendering

目前,我正在做一个简单的 React 练习。

我正在尝试根据特定状态有条件地渲染 jsx 的特定部分。

基本上,我的代码是这样的

const ShopList = (props) => {

    const [isLoading, setIsLoading] = useState(false)
    const [isEnd, setIsEnd] = useState(false)

    const handleButtonClick = ()=>{
        setIsLoading(true)
        axios.get('https://codingapple1.github.io/shop/data2.json')
        .then((result)=>{
            setTimeout(()=>props.addData(result.data),2000)
        })
        .then(()=>{
            setIsEnd(true)
        })
        .catch((e)=>{
            console.log(e)
            setIsLoading(false)
        })
    }

    return(
        <div className="container">
            <div className="row">
                {props.shoes.map((shoe,i) => (
                    <Product shoe={shoe} ind={i+1} key={shoe.id}/>
                ))}
            </div>
            {isLoading && <h3>Loading....</h3>}
            {!isEnd && <button className="btn btn-light" onClick={handleButtonClick}>More Items</button>}
        </div>
    )
}

export default ShopList;

问题是我找不到我的 setIsLoading(false) 以便我可以在两秒后隐藏 <h3>Loading...</h3>

我应该把 setIsLoading(false) 放在 handleButtonClick 函数的哪一部分?

回答您的问题,您很可能需要在这两种情况下隐藏“正在加载”: 请求是否成功。 所以你可以在 finally 部分这样做:

axios.get(...)
  .then(...)
  .catch(...)
  .finally(() => setIsLoading(false));