【发布时间】:2019-08-04 16:12:20
【问题描述】:
我在 React 中有以下方法,它检查 params.data 中的用户名是否存在于用户列表中。如果用户在场,我们将呈现正常的详细信息视图。如果没有,我们会显示 404 页面。
validateUsername = (match, params) =>
listUsers().then(({ data }) => {
if (Array.isArray(data.username).contains(params.username)) {
return true;
}
return false;
});
这件事奏效了。它有效,魅力,我每次都被重定向到正确的渲染中。但是我得到了这个错误,我正试图消除这个错误,因为我正计划测试这种情况。
这是组件:
import { getUser, listUsers } from '../../config/service';
// The above are the services I use to call specific endpoint,
// They return a promise themselves.
class UserDetailsScreen extends Component {
static propTypes = {
match: PropTypes.shape({
isExact: PropTypes.bool,
params: PropTypes.object,
path: PropTypes.string,
url: PropTypes.string
}),
label: PropTypes.string,
actualValue: PropTypes.string,
callBack: PropTypes.func
};
state = {
user: {}
};
componentDidMount() {
this.fetchUser();
}
getUserUsername = () => {
const { match } = this.props;
const { params } = match; // If I print this, it is fine.
return params.username;
};
fetchUser = () => {
getUser(this.getUserUsername()).then(username => {
this.setState({
user: username.data
});
});
};
validateUsername = (params) =>
listUsers().then(({ data }) => {
// Data are printed, just fine. I get
// the list of users I have on my API.
if (Array.isArray(data.username).contains(params.username)) {
// The error is here in params.username. It is undefined.
return true;
}
return false;
});
renderNoResourceComponent = () => {
const { user } = this.state;
return (
<div className="center-block" data-test="no-resource-component">
<NoResource
... More content for the no user with that name render
</NoResource>
</div>
);
};
render() {
const { user } = this.state;
const { callBack, actualValue, label } = this.props;
return (
<div className="container-fluid">
{user && this.validateUsername() ? (
<Fragment>
<div className="row">
...More content for the normal render here...
</div>
</Fragment>
) : (
<div className="container-fluid">
{this.renderNoResourceComponent()}
</div>
)}
</div>
);
}
}
export default UserDetailsScreen;
不知道哪里出了问题,也许我打电话时数据不存在,我需要 async-await 什么的。我需要帮助。谢谢!
【问题讨论】:
-
它不起作用。
Array.isArray返回一个布尔值,布尔值没有.contains方法(也没有任何其他 JS 值) -
好的,所以即使我删除它,它也不会停止抱怨。实际的解决方案是什么?我做错了吗?
-
那么还有一个错误...
-
user && this.validateUsername() ? … : …不起作用。validateUsername返回一个永远真实的承诺。 -
嗯,它报告了什么类型错误?
标签: javascript reactjs async-await es6-promise