从组件上的函数分派访问值

时间:2019-05-30 08:18:52

标签: reactjs react-native react-redux redux-thunk

我是新来的人。

我有一个函数,需要根据组件上的API请求结果刷新状态。

我如何获取该值?

代码(示例):

LoginComponent.js

        class Login extends React.Component {
           constructor(props){
              super(props)
              this.state = {
                 username : '',
                 password : ''
              }
           }
           submit = (e) => {
              /* console.logging "Some response"*/
              console.log(this.props.doLogin(this.state))
           }
           render(){
              return (
                 <form onSubmit={this.submit}>/* some login element */</form>
              )
           }
        }

export default connect(null, {LoginAction})(Login);

LoginAction.js

export function doLogin(state){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      return "Some response";

    })
   }
}

1 个答案:

答案 0 :(得分:0)

你可以这样做

例如创建axios.js

import axios from 'axios';

var instance = axios.create({
      baseURL: 'https://www.',
      timeout: 1000,
      headers: {'Authorization': 'Bearer xxx'}
});
export default instance;

然后在另一个屏幕上

import React from 'react';
import API from '../axios';


export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      feedback: "",
      id: "",
      errors: {},
    };
}


  postComment = () => {
        API.post(`/new-comment`, {
          id: this.state.id,
          feedback: this.state.feedback,
        })
        .then(res => res.data)
        .then((response)=> {
          this.setState({
              feedback: '',
              error: response.error || null,
          })

        }).catch(error => {console.log(error), this.setState({ error});});
   }