我正在使用Laravel和React Native来构建项目。我有一个post请求,它验证服务器端的数据并返回错误。我想在已声明状态的errors数组中分配错误响应。我的代码如下:
Laravel:
public function registerUser(Request $request)
{
$rules = [
'username' => 'required',
'email' => 'required|email',
'password' => 'required|min:5'
];
$validator = \Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json(['errors' => $validator->messages()]);
}
$user = User::create(request(['username', 'email', 'password']));
return response()->json('success');
}
React Native:
constructor(props){
super(props);
this.state={
userName:'',
userEmail:'',
userPassword:'',
errors:[]
}
}
axios({
method: 'post',
url: API_URL+'signup',
data: {
username: userName,
email: userEmail,
password: userPassword
}
})
.then(function (response) {
var count = Object.keys(response.data.errors).length;
if (count > 0) {
console.log(response.data.errors);
var newState = new Array();
newState.push(response.data.errors);
this.setState({
errors: newState
})
}
})
.catch(function (error) {
console.log(error);
});
它在控制台显示以下错误时显示错误:
undefined不是一个函数(评估' this.setState({errors:newState})') * app \ components \ Registration \ RegistrationForm.js:51:18 in - tryCallOne中的node_modules \ promise \ setimmediate \ core.js:37:14 - node_modules \ promise \ setimmediate \ core.js:123:25 in - ......来自框架内部的10多个堆栈框架
答案 0 :(得分:0)
您需要正确绑定函数以获取正确的this
上下文或使用已绑定到正确的this
上下文的ES6箭头函数
检查以下代码
axios({
method: 'post',
url: API_URL+'signup',
data: {
username: userName,
email: userEmail,
password: userPassword
}
})
.then((response) => {
var count = Object.keys(response.data.errors).length;
if (count > 0) {
console.log(response.data.errors);
var newState = new Array();
newState.push(response.data.errors);
this.setState({
errors: newState
})
}
})
.catch((error) => {
console.log(error);
});