我刚刚开始在React应用程序中实现Redux,这是我第一次尝试,所以请耐心等待。
我的问题是,我无法访问我的组件中的数据this.props.questions
我有一个简单的动作,应该异步获取一些数据
export function fetchQuestions(url) {
const request = axios.get('url');
return (dispatch) => {
request.then(({data}) => {
dispatch({ type: 'FETCH_QUESTIONS', payload: data });
console.log(data);
});
};
}
选择了我的减速机questions_reducer
export default function(state = [], action) {
switch(action.type) {
case 'FETCH_QUESTIONS':
console.log('Getting here');
return state.concat([action.payload.data]);
console.log('But not here');
}
return state;
}
我的index
缩减器看起来像这样:
import { combineReducers } from 'redux';
import fetchQuestions from './question_reducer';
const rootReducer = combineReducers({
questions: fetchQuestions
});
export default rootReducer;
我将它传递到我的商店,在那里我应用了thunk
中间件,最后进入<Provider store={store}>
包装我的应用程序,但道具只是在我的React组件中返回undefined
configureStore:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
}
我不知道console.log是否值得信任,但是在我的行动中从调度中返回数据之前,它会从我的questions_reducer中记录
编辑(组件)
class QuestionsRoute extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
this.props.fetch('someUrl);
setTimeout(function(){ console.log(this.props.questions) },
1500);
}
render() {
{console.log(this.props.questions)}
return (
<div>
<1>Hello</1>
{this.props.questions !== undefined ?
<p>We like props</p>: <p>or not</p>
}
</div>
);
}
};
const mapStateToProps = (state) => {
return {
questions: state.questions,
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetch: () => dispatch(fetchQuestions())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(QuestionsRoute);
答案 0 :(得分:2)
在减速机中
export default function(state = [], action) {
switch(action.type) {
case 'FETCH_QUESTIONS':
return state.concat([action.payload.data]);
}
return state;
}
您应该改为return state.concat([action.payload]);
从dispatch({ type: 'FETCH_QUESTIONS', payload: data });
开始,我们发现payload
data
,但它并不包含它。
更新:我建议您设置redux-devtools
/ redux-devtools-extension
/ react-native-debugger
,这样您就可以直观地看到自己的行为并实时存储状态 - 让这样的事情变得更容易调试!