gpt4 book ai didi

react-native - 如何使用 redux-saga 传递参数

转载 作者:行者123 更新时间:2023-12-03 15:10:48 24 4
gpt4 key购买 nike

作为 react-native 和 redux-saga 的练习,我正在尝试开发一个小天气应用程序。

虽然获取和呈现数据工作正常,但我以某种方式难以将参数从 TextInput 传递到最终的 API 调用。

现在的目标只是将 cityName 字符串传递给 api.js 和 console.log 中的 fetchWeather 函数。

props.requestWeather(cityName) 开始在 Main.js 中

我尝试了各种方法通过 action 和 saga 将 cityName 传递给 apiCall,这让我意识到,我比其他任何事情都在猜测。遗憾的是,以下研究也没有成功,所以我们来了。

关于如何将字符串作为参数传递和/或对以下 redux 设置的一般批评的任何想法都将受到高度赞赏!

戴夫

主程序

//[...] setCity Name to TextInput component
const [cityName, setCityName] = useState('')
// [...] calling the action (inside onClickHandler)
props.requestWeather()
//[...]
const mapStateToProps = state => ({
weatherData: state.weatherData
});

const mapDispatchToProps = dispatch =>
bindActionCreators({ requestWeather }, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(Main);

Action .js
export const REQUEST_WEATHER = "REQUEST_WEATHER"
export const RECEIVE_WEATHER = "RECEIVE_WEATHER"

export const requestWeather = () => ({ type: REQUEST_WEATHER })
export const receiveWeather = weatherData => ({ type: RECEIVE_WEATHER, weatherData })

sagas.js
function* getWeather(action) {
try {
const weatherData = yield call(fetchWeather);
yield put(receiveWeather(weatherData));
} catch (e) {
console.log(e);
}
}

function *watchAll() {
yield all([
//[...]
takeLatest(REQUEST_WEATHER, getWeather)
]);
}
export default watchAll;

api.js
export const fetchWeather = async () => {

const APPID = process.env.WEATHER_API_KEY

try {
let weatherData = []
const weather1Promise = axios('https://api.openweathermap.org/data/2.5/weather?q=Rom&APPID='+APPID)
//[...]
const [weather1, weather2, weather3] = await Promise.all([weather1Promise, weather2Promise, weather3Promise]);
weatherData.push(weather1.data, weather2.data, weather3.data)
return weatherData
}
catch (e) {
console.error(e)
}
}

最佳答案

首先,您需要修改您的操作以接受 cityName :

export const requestWeather = (cityName) => ({ type: REQUEST_WEATHER, cityName });
然后在传奇中:
const weatherData = yield call(fetchWeather, action.cityName);
...最后是内部请求:
export const fetchWeather = async (cityName) => {
console.log(cityName); // will log entered city name

关于react-native - 如何使用 redux-saga 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com