我正在尝试将类组件转换为功能组件,以利用React.useState钩子和React.use Effect钩子。组件正在请求检查服务器上是否存在令牌。
import React, { Component } from 'react';
import { Loader, Dimmer, Transition, Message } from 'semantic-ui-react';
import axios from 'axios';
import { hasBeenVerified } from '../../store/reducers/users/index';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
function Confirmation({ match, isAccountVerified, hasBeenVerified }) {
var [token, setToken] = React.useState(null);
var [duration, setDuration] = React.useState(500);
var [responseMessage, setResponseMessage] = React.useState({});
var [error, setError] = React.useState(false);
React.useEffect(() => {
console.log('token ', token);
axios
.get(`http://localhost:8016/users/confirmation/${setToken(match.params.token)}`)
.then(response => {
if (response.status === 200) {
hasBeenVerified();
setResponseMessage(response.data.msg);
return;
}
})
.catch(function(error) {
if (error.response.status === 404) {
setResponseMessage(error.response.data.msg);
setError(true);
return;
}
if (error.response.status === 400) {
setResponseMessage(error.response.data.msg);
setError(true);
return;
}
});
return () => {
setToken(null);
setResponseMessage({});
setError(false);
};
}, [token, isAccountVerified, hasBeenVerified, setResponseMessage, setError]);
console.log('token ', token);
console.log('isAccountVerified ', isAccountVerified);
console.log('match', match);
console.log('responseMessage', responseMessage);
return (
<div className="login-form">
<Transition
visible={isAccountVerified}
unmountOnHide={true}
animation="scale"
duration={duration}
>
{!isAccountVerified ? (
<Dimmer active inverted>
<Loader />
</Dimmer>
) : (
<Message success={!error} error={error} header={responseMessage[0]} />
)}
</Transition>
</div>
);
}
function mapStateToProps(state) {
const { users } = state;
const { isAccountVerified } = users;
return { isAccountVerified };
}
const mapDispatchToProps = dispatch => bindActionCreators({ hasBeenVerified }, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(Confirmation);
我向依赖数组添加了值,因为它是依赖的外部值。我还添加了指定的清理函数。
有人能提供一些见解吗?为什么它根本不起作用,即成功,不同的错误结果?
您在异步调用后返回。所以你的状态肯定变成了{}
。
将[token, isAccountVerified, hasBeenVerified, setResponseMessage, setError]
更改为[]
,效果良好。
此数组用于运行useEffect回调函数以更改其值。您传递了函数?!
即使你破坏了Component
,但从不使用它。你的代码读起来非常嘈杂。
import React, { useState, useEffect } from 'react';
~~~
useEffect(() => {
console.log('token ', token);
axios.get('http://localhost:8016/users/confirmation/${setToken(match.params.token)}')
.then(response => {
if (response.status === 200) {
hasBeenVerified();
setResponseMessage(response.data.msg);
// return;
}
})
.catch(function(error) {
if (error.response.status === 404) {
setResponseMessage(error.response.data.msg);
setError(true);
// return;
}
if (error.response.status === 400) {
setResponseMessage(error.response.data.msg);
setError(true);
// return;
}
});
/* return () => { // this commented part run exactly after asynchronous axios call. you don't need this part.
setToken(null);
setResponseMessage({});
setError(false);
}; */
}, []);
我在下面基于Airbnb ESLint标准编写了一个常见的ReactJS代码。
-
我不明白为什么要使用析构函数赋值导入
Component
。它是一个函数组件,所以只需通过析构函数赋值导入useState
和useEffect
即可。 -
为什么在组件内部调用API调用。这不是一种常见的方式,将其写入另一个文件并导入,或者使用
redux
操作调度来调用API并从redux中获取API数据。这两种方式都很常见。 -
永远不要在JavaScript逻辑代码中编写内容。把它写在另一个文件中,然后导入。这意味着你应该把你的URL路径分开。就像分离API调用一样。
-
上帝显示了他的仁慈,你为什么不使用这种仁慈?我是说
async/await
。毫无疑问,它使所有代码都更可读。 -
对嵌套值(如
match.params.token
(使用可选的链接。
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Loader, Dimmer, Transition, Message } from 'semantic-ui-react';
import { hasBeenVerified } from '../../store/reducers/users';
import { confirmCall } from '[pathTo]/api'; // pseudo code
const Confirmation = ({
match,
isAccountVerified,
hasBeenVerified
}) => {
const [token, setToken] = useState(null);
const [duration, setDuration] = useState(500);
const [responseMessage, setResponseMessage] = useState({});
const [error, setError] = useState(false);
useEffect(async () => {
try {
const response = await confirmCall(match?.param?.token);
if (response.status === 200) {
hasBeenVerified();
setResponseMessage(response.data.msg);
}
} catch (error) {
if (error.response.status === 404) {
setResponseMessage(error.response.data.msg);
setError(true);
}
if (error.response.status === 400) {
setResponseMessage(error.response.data.msg);
setError(true);
}
}
}, []);
return (
<div className="login-form">
<Transition
visible={isAccountVerified}
unmountOnHide={true}
animation="scale"
duration={duration}
>
{!isAccountVerified ? (
<Dimmer active inverted>
<Loader />
</Dimmer>
) : (
<Message
success={!error}
error={error}
header={responseMessage[0]}
/>
)}
</Transition>
</div>
);
}
const mapStateToProps = ({ users: { isAccountVerified } }) => ({
isAccountVerified
});
const mapDispatchToProps = dispatch =>
bindActionCreators({ hasBeenVerified }, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(Confirmation);