【发布时间】:2021-12-29 11:52:20
【问题描述】:
我有一个 Home.js 组件,它让用户注册 API 并登录,然后获取从响应授权标头接收到的令牌并将其保存在 state 'token' 变量中。
此令牌将在所有其他组件中用于在发出请求时访问 API,那么将此值用于所有其他组件的最佳方式是什么?
Home.js:
const SIGNUP_URL = 'http://localhost:8080/users/signup';
const LOGIN_URL = 'http://localhost:8080/login';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated:false,
token: ''
};
}
componentDidMount() {
const payload = {
"username": "hikaru",
"password": "JohnSmith72-"
};
fetch(SIGNUP_URL, {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
})
.then(response => response.json())
.then((data) => {
console.log(data);
});
fetch(LOGIN_URL, {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
})
.then(response =>
this.setState({token: response.headers.get("Authorization"), isAuthenticated:true})
)
}
例如 userList 组件将从 API 中获取用户数据,但需要存储在 Home 组件的令牌状态变量中的 API 令牌才能通过授权标头成功发送请求。
感谢您的帮助
【问题讨论】:
标签: javascript reactjs json react-native request