【问题标题】:Access value from function dispatch on component从组件上的函数调度访问值
【发布时间】:2019-10-15 21:05:52
【问题描述】:

我是新手。

我有一个函数,需要根据我的组件上的 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";

    })
   }
}

【问题讨论】:

  • 当 Promise 被解决时,只需在你的 axios thenable 中调用 dispatch 函数,并让它更新你的 redux 存储中的一个布尔值,说明你是否登录
  • 你能创建一个例子吗?并登录它只是一个示例,它包含更多基础知识,例如反馈是否有效

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


【解决方案1】:

你可以这样做

例如创建 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});});
   }

【讨论】:

  • 在这种情况下我需要使用 redux。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
相关资源
最近更新 更多