【发布时间】:2020-04-15 15:26:53
【问题描述】:
我是 React 和 Redux 的新手,目前正在尝试使用故事 ID 从我的数据库中获取单个故事(ID、标题、内容、音频)。我已经设置了组件、动作和减速器。
但是我在组件中遇到了以下错误:
无法读取未定义的属性“then”
getStory(id) {
> 31 | this.props.getSingleStory(id)
| ^ 32 | .then(response => {
33 | this.setState({
34 | story: response.data
故事细节组件
import {getSingleStory } from '../../actions/story';
....
export class StoryDetails extends Component {
constructor(props) {
super(props);
this.getStory = this.getStory.bind(this);
this.state = {
story: {
id: null,
title: "",
content: "",
audio: ""
}
};
}
componentDidMount() {
this.getStory(this.props.match.params.id);
}
getStory(id) {
this.props.getSingleStory(id)
.then(response => {
this.setState({
story: response.data
});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
render() {
const { story } = this.state;
return (
<Fragment>
<h2>Stories</h2>
{story.title}
{story.content}
</Fragment>
);
}
}
const mapStateToProps = state => ({
story: state.story.story
});
export default connect(
mapStateToProps,
{ getSingleStory}
)(StoryDetails);
动作(动作在类型中注册)
// GET SINGLE STORY
export const getSingleStory = id => (dispatch, getState) => {
axios
.get( apiBase + `/story/${id}/`, tokenConfig(getState))
.then(res => {
dispatch({
type: GET_SINGLE_STORY,
payload: res.data
});
})
.catch(err =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};
减速器
case GET_SINGLE_STORY:
return {
...state,
story: state.story.filter(story => story.id !== action.payload)
};
据我所知,我的 GET_SINGLE_STORY 操作返回“res.data”。所以我不明白为什么'then'是未定义的。
感谢任何提示!
【问题讨论】:
-
您是否使用 thunk 作为中间件,因为您的函数是异步的?不确定您的 mapDispatchToProps 当前是否设置...
标签: javascript reactjs redux axios