我在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之类的东西。我需要一些帮助。谢谢!
答案 0 :(得分:0)
如注释中所述,Array.isArray()
返回为布尔值,并且无法对布尔值调用数组方法,需要检查data.username
是否为数组,然后在其上单独运行方法。
我还认为您应该使用includes而不是contains
要处理.then
中发生的错误,您可以链接.catch
,该函数接受一个函数作为参数。您提供的函数将收到错误作为参数供您处理。
const examplePromise = new Promise(resolve => {
const data = {
username: ['a','b', 'c']
}
setTimeout(() => {
resolve({data});
}, 1000);
})
examplePromise.then(({data}) => {
console.log(data.username.contains('a'))
}).catch(err => {
// VM1025 pen.js:13 Uncaught (in promise) TypeError: data.username.contains is not a function
console.log(err)
})
examplePromise.then(({data}) => {
console.log('works', data.username.includes('a'))
}).catch(err => {
console.log(err)
})