【发布时间】: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