Redux 我试图发出一个动作,但它似乎没有注册
我试图在某个阶段向减速器发送操作,但它似乎不起作用。当安装组件时,将启动showGeo()函数。我在控制台中看到的只是一个默认状态的空数组。我尝试过用dispatch将代码包装在返回块中,但这也不起作用。我是redux的初学者,因此任何帮助都将不胜感激Redux 我试图发出一个动作,但它似乎没有注册,redux,react-redux,redux-thunk,Redux,React Redux,Redux Thunk,我试图在某个阶段向减速器发送操作,但它似乎不起作用。当安装组件时,将启动showGeo()函数。我在控制台中看到的只是一个默认状态的空数组。我尝试过用dispatch将代码包装在返回块中,但这也不起作用。我是redux的初学者,因此任何帮助都将不胜感激 export const sendAction = (user) => { return (dispatch) => { dispatch({ type: GEO_SUCCESS, payload: user });
export const sendAction = (user) => {
return (dispatch) => {
dispatch({ type: GEO_SUCCESS, payload: user });
};
};
export const showGeo = () => {
const firebaseRef = firebase.database().ref('/geofire');
const geoFire = new geofire(firebaseRef);
let user;
const geoQuery = geoFire.query({
center: [37.78, -122.4],
radius: 10 //kilometers
});
geoQuery.on("key_entered", function(key, location, distance) {
console.log("Bicycle shop " + key + " found at " + location + " (" + distance + " km away)");
firebase.database().ref('/users/' + key).once('value').then(function(snapshot) {
console.log(snapshot.val());
user = snapshot.val();
sendAction(user);
});
});
};
以下是reducer文件:
import {
GEO_SUCCESS
} from '../actions/types';
export default (state = [], action) => {
switch (action.type) {
case GEO_SUCCESS:
return action.payload;
default:
return state;
}
};
好的,我想我看到你的问题了。您没有在正确的功能中使用
dispatch
。如果在组件中使用showGeo
,则必须让Redux将dispatch
注入showGeo
函数,以便可以调度sendAction
函数。因此showGeo
应该类似于sendAction
这样:
showGeo = () => {
return dispatch => {
//...
dispatch(sendAction()) // where this dispatches the action
}
}
您可以使用Redux的mapDispatchToProps在组件中注入dispatch
我建议你看一下和。我建议浏览一下教程,更好地掌握这两个方面。嗨,我忘了提到user是一个全局变量,可以通过sendAction访问。无论如何,我会试试你的建议。谢谢。。。。为什么它是一个全局变量?您正在使用redux并分派一个操作以将用户包括在其中。没有真正的原因,我更改了代码以按照您的建议将其作为参数提供,但该操作仍然没有更新用户的状态。