简体   繁体   English

背景图像不显示内联反应

[英]Background Image not displaying Inline React

The goal is to display different backgrounds depending on the fetched weather data.目标是根据获取的天气数据显示不同的背景。 I'm trying to set the background inline in the JSX.我正在尝试在 JSX 中设置背景内联。 On the first fetch, the data is populated but the background doesn't change until I click the search icon again.在第一次提取时,数据已填充,但背景不会改变,直到我再次单击搜索图标。 I've tried bundling both the fetch function and background handler function in one function then setting that function onClick and I've tried adding the backgroundHandler at the end of the fetch function. I've tried bundling both the fetch function and background handler function in one function then setting that function onClick and I've tried adding the backgroundHandler at the end of the fetch function. Both require an additional click after the initial fetch.两者都需要在初始获取后额外点击。 On each occasion, you can see a 404 error on the initial fetch to populate the data.在每种情况下,您都可以在初始提取以填充数据时看到 404 错误。 The photo I'm testing is imported into React as (cloudy).我正在测试的照片以(多云)的形式导入 React。

Both Functions bundled into RenderUI Function两个函数都绑定到 RenderUI Function

const WeatherContainer = () => {
    const [searchTerm, setsearchTerm] = useState()
    const [currentWeather, setCurrentWeather] = useState({});
    const [forecastedWeather, setForecastedWeather] = useState({});
    const [loading, setLoading] = useState(false);
    const [background, setBackground] = useState()
    
    const handleInput = (e) => {
        setsearchTerm(e.target.value);
    }

    // Dynamically changes background depending on current weather
    const backgroundHandler = () => {
        // Day Backgrounds
        if (Object.keys(currentWeather).length > 0) {
             if (currentWeather.weather[0].icon === '02d' || currentWeather.weather[0].icon === '04d' ) {
                setBackground(cloudy)
            }
        }
    };
    
    const handleSearch = () => {
        fetch(`/weather/${searchTerm}`)
            .then(res => { return res.json() })
            .then(result => {
                setCurrentWeather({ ...result.data })
            })
    };

    const renderUI = () => {
        handleSearch();
        backgroundHandler();
    }


    return (
        <div>
            <div className='search-bar'>
                    <input className='text_input' type='text' name='searchTerm' onChange={handleInput} placeholder='Enter city' />
                    <button className='search-button' onClick={renderUI} type='submit' value='submit' name='button'>
                        <Icon icon={searchIcon} flip="horizontal" />
                    </button>
            </div>
            
            <div className='weather-container' style={{ backgroundImage: `url(${background})` }}>
                {Object.keys(currentWeather).length > 0
                    ? <>
                        <CurrentWeatherComponent
                            currentWeather={currentWeather}/>
                        <ForecastContainer />
                      </>
                    : <></>
                }
            </div>  
        </div>
    )

};

在此处输入图像描述

BackgroundHandler called at the end of handleSearch Function在 handleSearch Function 结束时调用的 BackgroundHandler

const WeatherContainer = () => {
    const [searchTerm, setsearchTerm] = useState()
    const [currentWeather, setCurrentWeather] = useState({});
    const [forecastedWeather, setForecastedWeather] = useState({});
    const [loading, setLoading] = useState(false);
    const [background, setBackground] = useState()
    
    const handleInput = (e) => {
        setsearchTerm(e.target.value);
    }

    // Dynamically changes background depending on current weather
    const backgroundHandler = () => {
        // Day Backgrounds
        if (Object.keys(currentWeather).length > 0) {
             if (currentWeather.weather[0].icon === '02d' || currentWeather.weather[0].icon === '04d' ) {
                setBackground(cloudy)
            }
        }
    };
    
    const handleSearch = () => {
        fetch(`/weather/${searchTerm}`)
            .then(res => { return res.json() })
            .then(result => {
                setCurrentWeather({ ...result.data })
            })
        backgroundHandler();
    };

    return (
        <div>
            <div className='search-bar'>
                    <input className='text_input' type='text' name='searchTerm' onChange={handleInput} placeholder='Enter city' />
                    <button className='search-button' onClick={handleSearch} type='submit' value='submit' name='button'>
                        <Icon icon={searchIcon} flip="horizontal" />
                    </button>
            </div>
            
            <div className='weather-container' style={{ backgroundImage: `url(${background})` }}>
                {Object.keys(currentWeather).length > 0
                    ? <>
                        <CurrentWeatherComponent
                            currentWeather={currentWeather}/>
                        <ForecastContainer />
                      </>
                    : <></>
                }
            </div>  
        </div>
    )

};

在此处输入图像描述

Change backgroundHandler to a useEffect with currentWeather as a dependency (just copy the function body and put inside it).backgroundHandler更改为useEffect并以currentWeather作为依赖项(只需复制 function 主体并放入其中)。 useState is async and may not be set yet when you run backgroundWeather , that's why its blank useState是异步的,并且在您运行backgroundWeather时可能尚未设置,这就是为什么它为空白

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

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