【发布时间】:2017-08-19 19:20:44
【问题描述】:
问题
我在 redux 中有一个异步函数(带有 redux thunk),它在 redux 存储中设置了一个值。它在我的应用程序中多次使用,但是,我希望在使用 redux 函数设置的新值运行 redux 函数后发生不同的事情。似乎是一个很好的回调理由,对吧?所以我尝试这样做,但出现以下错误:
未捕获的类型错误:无法读取未定义的属性 'then'
尝试修复的逻辑
我认为原因可能是尽管redux 函数调度了动作,但它实际上并没有返回任何东西。因此,我在 redux 函数中添加了returns,认为该函数会将某些内容返回给调用它的组件,这将解决我收到的错误。运气不好。
问题:
有谁知道我如何在异步 redux 函数(带有 redux thunk)运行并完成在 redux 存储中设置新值之后执行功能?
我最近尝试解决的问题
组件
import {fetchUser} from './../actions/index.js';
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
// Attempt #1: this.props.fetchUserData()); // originally I attempted just running one function and then the rest without a callback but the new value was not set in redux store before the next function that needed it ran
// Attempt #2: this.props.fetchUserData().then(function() => { // I also tried running just a standard .then(function()
// Attempt #3: (line below)
this.props.fetchUserData().then((resultFromReduxFunction) => {
console.log("fetchUserData result = " + resultFromReduxFunction);
// do some stuff with the new data
console.log("this.props.reduxData.userHairColor = " + this.props.reduxData.userHairColor);
console.log("this.props.reduxData.userHeight = " + this.props.reduxData.userHeight);
});
}
}
function mapStateToProps(state) {
return {
reduxData: state.user
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
fetchUserData: fetchUserData
}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(MyComponent);
动作创建者
export const set = (idToSet, payloadToSet) => {
return {
type: 'SET',
id: idToSet,
payload: payloadToSet
}
}
export const fetchUserData = (callbackFunction) => {
console.log("fetchUserData triggered...");
return (dispatch, getState) => {
firebase.auth().onAuthStateChanged(function (user) {
if (!user) {
console.log("no user logged in");
return false // Added in attempt to fix callback
} else {
// fetch some more user data
firebase.database().ref().child('users').child(user.uid).on('value', function(snapshot) {
var userHairColor = snapshot.child(userHairColor).val();
var userHeight = snapshot.child(userHeight).val();
dispatch(set('userHairColor', userHairColor));
dispatch(set('userHeight', userHeight));
return true // Added in attempt to fix callback
})
}
})
}
}
Redux 商店
const initialState = {
userHairColor: "",
userHeight: ""
}
export default function (state=initialState, action) {
switch(action.type) {
case 'SET':
return {
...state,
[action.id]: action.payload
}
default:
return {
...state
}
}
}
提前感谢您的帮助
【问题讨论】:
-
dispatch(set('userHairColor', userHairColor));set是动作创建者吗?显示它,如果是的话。 -
这是一个reducer,我想看看action creator。
-
添加了
SET动作创建者 -
一切看起来都正确,您的第一个变体应该可以工作...
-
在第一个变体中,
userHeight和userHairColor在 redux 函数运行后我的函数还没有任何东西(我猜是因为调用了 redux 函数但异步函数在设置这些值之前需要一些时间,同时我的componentDidMount中的其余内容现在已经运行)
标签: javascript reactjs firebase redux redux-thunk