2017-11-18 6 views
0

"login, register, createPost"등과 같이 백엔드와 통신하는 다양한 메소드가있는 API 클래스가 있습니다.이 클래스를 감속기에 연결하고 있습니다. 감속기는 내 API를 클래스에 액세스 할 수 있도록 할 사용자 정보의 state 포함 : 첫 번째 방법에서redux를 사용하는 클래스의 인스턴스를 인스턴스화하는 방법

import axios from 'axios'; 
import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 

@connect(state => ({ 
    api: state.api, 
})) 
export default class Api extends Component { 

    export const login = async({args}) => { 

    const url = this.props.api.url.concat('/login/'); 
    const config = { 
     headers: { 
      'X-CSRFTOKEN': this.props.api.token 
      } 
     }; 
    try { 
     const data = await axios.post(url, {"username": args.username, "password": args.password}, config); 
     this.props.api.key = data.data.token; 
     this.props.api.user = data.data.user; 
     return data; 
    } catch (e) { 
     throw e; 
     } 
    } 
}; 

    async createPost(args (content of the post)) { 
     try { 
      const url = this.props.api.url.concat('/post/PostList'); 
      const Response = await axios.post(url, {...args}, !**this.props.api.key**!); 
      return Response; 
     } catch (e) { 
      throw e; 
     } 
    } 

를, 내가 가져온 state.key 및 state.user을 설정 (REDUX를 통해 연결) 정보 , 나는 두 번째 방법 (this.props.api.key 별에 둘러싸여 있음)에서 접근하려고합니다. 나는 다른 화면에서 많은 동작을하기 때문에이 방법을 시도하고 있으며 사용자는 인증 정보를 API 메소드에 전달해야합니다. 각각의 동작을 실행합니다. 액션이라고 부르는 모든 다른 파일에 Api 상태를 가져 오는 대신 Api 클래스에서 사용자 정보를 전달하는 것이 더 쉽다는 것을 알았습니다.

문제는 내가 새 객체를 인스턴스화 할 수 없다는 것입니다. 그것은 나에게 오류를 제공하기 때문에

const api = new Api(); 

같은 API를 "정의의 속성 저장소를 읽을 수 없습니다"그래서 각각의 파일에 (withArgs를) api.login 작업을 호출 할 수 없습니다, 나는 방법은 정적 만들 경우 그들은 이것에 접근 할 수 없을 것입니다 .props.whatever

세계적인 redux의 상태에 연결된 클래스를 어떻게 인스턴스화 할 수 있습니까? 내 감속기 파일 밖의 그 세계 상태에 관한 정보?

답변

0

Api가 React.Component를 확장 한 이후 React가 직접 렌더링하는 대신 클래스를 인스턴스화하려는 이유는 무엇입니까?

ReactDOM.render(<Api store={store} />) 

하거나

ReactDOM.render(React.createElement(Api, { store }) 
JSX

을 사용하지 않는 경우
관련 문제