我是第一次尝试,所以请耐心等待 . 我的问题是我无法访问我的组件中的数据 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
reducer看起来像这样:
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);
1 回答
在你的减速机
你可能应该改为
return state.concat([action.payload]);
从
dispatch({ type: 'FETCH_QUESTIONS', payload: data });
开始,我们看到payload
是data
,它不包含它 .更新:我建议设置
redux-devtools
/redux-devtools-extension
/react-native-debugger
,以便您可以直观地看到您的操作和实时存储状态 - 使这样的事情更容易调试!