代码之家  ›  专栏  ›  技术社区  ›  J.Kennsy

存储字段的共享方法

  •  0
  • J.Kennsy  · 技术社区  · 6 年前

    动机


    州/授权

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


    有没有办法创造这样一个? 任何帮助都将不胜感激
    1 回复  |  直到 6 年前
        1
  •  1
  •   adz5A    6 年前

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

    首先,错误来自传球 fetchData 的返回值 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 应用到任何组件中。这个props是一个函数,它使用用户的凭据来分派操作。它还将注入 user
    • 在redux中间件中,您可以捕获操作并使用 获取数据 处理请求。当请求被解决时,您将动作分派给reducer并更新它。组件本身没有数据获取,所有事情都在中间件级别处理。