状态不更新组件(React)



我用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

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

你需要返回state而不是return assign value to state

case "CHANGE_CITY":
return action.payload;

相关内容

  • 没有找到相关文章

最新更新