Redux 및 React를 사용하여 데이터베이스에서 단일 데이터 요소를 얻는 방법은 무엇입니까?

댄 보이

저는 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'이 정의되지 않은 이유를 알 수 없습니다.

힌트 주셔서 감사합니다!

아민 모하마디

getSingleStory에서 promise를 반환해야합니다 (아무것도 반환하지 않음).

export const getSingleStory = id => (dispatch, getState) => {
    return new Promise((resolve, reject) => {
        axios.get( apiBase + `/story/${id}/`, tokenConfig(getState))
        .then(res => {
            dispatch({
                type: GET_SINGLE_STORY,
                payload: res.data
            });
            resolve(res);
         })
        .catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status));
            reject(err);
        });
   });
};

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관