【问题标题】:State not updating components (React)状态未更新组件 (React)
【发布时间】:2021-08-10 12:41:42
【问题描述】:

我使用 redux 制作了一个天气应用程序。现在,当应用程序加载时,状态发生了变化。但是当我尝试更改城市名称时,它并没有改变。

如何更改另一个组件的状态?

React.useEffect(() => {

        fetchLocation();

    }, [lat, long])
    
    
    
    const fetchLocation = async () => {
        await fetch("https://geolocation-db.com/json/")
            .then(res => res.json())
            .then(result => {
                scity(result.city);
                console.log(ccity);
                dispatch(changeCity(ccity));
                fetchWeatherByCity(result.city);
            });
    }
    const fetchWeatherByCity = async (city) => {
        
        await fetch(`${REACT_APP_API_URL}/weather/?q=${city}&units=metric&APPID=${REACT_APP_API_KEY}`)
            .then(res => res.json())
            .then(result => {

                setData(result);

                console.log(result);

                setState({});

            });
    };
dispatch(changeCity(ccity)); // changing the city 
// It is the current city, when the app loads
//First component
//changeCity action file
export const changeCity = (t) =>{
    return({
        type: "CHANGE_CITY",
        payload: t,
    });
}
//reducer file
const cn = (state = "", action) => {
    switch (action.type) {
        case "CHANGE_CITY":
            return state = action.payload;
       
        default:
            return state;
    }
}
export default cn;
// second component from where I want to change the city
<TextInput onChangeText={(value) => st(value)} style={styles.search_bar} placeholder="Another Location" placeholderTextColor="#fff"></TextInput>
<Button onPress = {()=> dispatch(changeCity(t))}></Button>


// this is second component

现在,我想从第二个组件更新城市名称。

【问题讨论】:

  • dispatch(changeCity(ccity)); 是在第一个组件的useEffect 内吗?那个 useEffect 在依赖数组里面有什么东西吗?
  • @Ammar 不,它不在第一个组件的useEffect

标签: javascript reactjs react-native redux react-redux


【解决方案1】:

你需要返回状态而不是返回赋值给状态

case "CHANGE_CITY":
   return action.payload;

【讨论】:

  • 它仍然无法工作,它会在 0.5 秒后重置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多