gpt4 book ai didi

javascript - 存储字段的共享方法

转载 作者:行者123 更新时间:2023-12-03 01:12:37 27 4
gpt4 key购买 nike

动机

我将用户凭据存储在 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: Cannot call a class as a function

<小时/>有没有办法创建这样一个?如有任何帮助,我们将不胜感激♥

最佳答案

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

首先,错误来自于将 fetchData 传递给 connect 的返回值:connect 返回一个 HOC 的函数。 :接受一个组件,返回一个组件,它是一个,不能像您一样作为函数调用。

解决您问题的方法是使用 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 会将 props logUser 注入(inject)到它所应用到的任何组件中。此 props 是一个使用用户的凭据调度操作的函数。它还会注入(inject)从 redux 状态获取的 user 属性,以便您向用户显示。
  • 在 redux 中间件内,您捕获操作并使用通用 fetchData 来处理请求。当请求得到解决后,您将操作分派(dispatch)给 reducer 并更新它。组件本身不会发生数据获取,一切都在中间件级别处理。

关于javascript - 存储字段的共享方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52151662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com