商店字段的共享方法

问题描述 投票:0回答:1

动机

我将用户凭据存储在redux商店中。用户登录时会填充它们。我希望有可重用的方法来获取用户用户名和密码的数据。


State / auth

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

My attempt

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);

Call

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

但是一旦我打电话给我,我得到:

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


Is there any way at all to create such one? Any help would be appreciated ♥
javascript reactjs typescript redux
1个回答
1
投票

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

首先,错误来自将fetchData传递给connect的返回值:connect返回一个函数,它是一个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并更新它。组件本身不会发生数据提取,一切都在中间件级别处理。
© www.soinside.com 2019 - 2024. All rights reserved.