商店字段的共享方法

时间:2018-09-03 14:23:35

标签: javascript reactjs typescript redux

动机

我将用户凭据存储在redux存储中。用户登录时它们已填满。我希望有一种可重用的方法来使用用户名和密码来获取数据。


状态/身份验证

const initState = {
    isLoading: false,
    user: undefined,
    auth_err: false
};

我的尝试

const fetchData = props => async (url, method, body) => {

    try {
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Basic ' + Base64.btoa(props.user.username + ":" + props.user.password)
            },
            body: body
        });
        console.log(response);
        return response;
    } catch (err) {
        console.log(err);
    }
};

const mapStateToProps = state => {
    return {
        user: state.auth.user
    }
};

export const SENDREQUEST = connect(mapStateToProps)(fetchData);

致电

const response = await SENDREQUEST("http://localhost:8080/users", "GET");

但是一旦我叫它,我就会得到:

  

TypeError:无法将类作为函数调用


有什么办法可以创建这样的一个? 任何帮助将不胜感激♥

1 个答案:

答案 0 :(得分:1)

我假设您了解redux及其中间件。

首先,错误来自将fetchData传递给返回值connectconnect返回的函数是HOC:接受一个组件,返回一个此处是class的组件,无法像您一样调用为函数。

您的问题的一种解决方案是使用mapDispatchToProps和中间件,大致如下:

class LoginFormPresenter {
  render () {
    // render your login
    return <form onSubmit={this.props.logUser}></form>
  }
}

// This makes the LoginFormPresenter always receive a props `logUser`
const LoginFormConnector = connect((state => { user: state.user }), {
  logUser: (e) => (
    // create a credentials object by reading the form
    const credentials = ...;

    // return a valid redux action
    return {
      type: "LOGIN",
      credentials
    };
  )
});
const LoginForm = LoginFormConnector(LoginFormPresenter);

// Create an ad hoc middleware
//
const middleware = ({ dispatch, getState }) => next => action => {

  if (action.type === "LOGIN") {
    // log your user
    fetch()
      .then(user => next({ type: "LOGIN", user }));

    return next({ type: "PROCESSING_LOGIN" }); // indicate to redux that you are processing the request
  }
  // let all others actions pass through
  return next(action);


};

该机制的工作原理如下:

  • LoginFormConnector将把道具logUser注入到要应用的任何组件中。该道具是一个功能,该功能可使用您的用户凭据调度操作。它还会注入来自redux状态的user道具,以向用户展示。
  • 在redux中间件中,您可以捕获操作并使用通用的fetchData处理请求。解决请求后,您将操作分派给reducer并更新它。组件本身没有数据获取,一切都在中间件级别处理。