我需要将刀片user.id传递给react js组件,但是我不断得到
app.js:56717 POST http://127.0.0.1:8000/user/follow/undefined 419 (状态未知)
我也遇到了类似的问题here,我已经接近了,但仍然不能帮助我解决问题。有什么建议吗?
Routes.php
Route::post('user/follow/{id}', 'UserController@my_follow');
Profile.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
export default class Example extends Component {
constructor(props){
super(props);
this.state = {
btnText: 'Follow',
className: 'follow-button',
user:{
id:this.props.data
}
};
}
myfollow(user) {
fetch('/user/follow/'+ this.state.user.id , { method: "POST" })
.then(response => response.json())
.then(response => {
console.log(response);
});
};
btnClick(){
this.myfollow(this.state.user.id);
if(this.state.btnText === 'Follow'){
this.setState({
btnText:'Following'
})
} else{
this.setState({
btnText: 'Follow'
})
}
if(this.state.className === 'follow-button'){
this.setState({
className: 'following-button'
})
}
else{
this.setState({
className: 'follow-button'
})
}
}
render(){
return (
<div className="followdoe">
<button onClick={this.btnClick.bind(this)} className={this.state.className}>
<p>{this.state.btnText}</p>
</button>
</div>
);
}
}
Profile.blade.php
<div id="profile" data='{{ $user->name }}'></div>
这是后端的样子
发布Controller.php
public function my_follow(Request $request, $id)
{
$user = auth()->user();
if($user->id != $id && $otherUser = User::find($id)){
$user->toggleFollow($otherUser);
}
}
答案 0 :(得分:0)
经过一些研究,我找到了解决方案,我需要改变几件事。
Profile.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
export default class Example extends Component {
constructor(props){
super(props);
let id = JSON.parse(this.props.data);
this.state = {
btnText: 'Follow',
className: 'follow-button',
user:{
id:id
}
};
}
myfollow(user) {
axios('/user/follow/'+ this.state.user.id , { method: "POST" })
.then(response => {
console.log(response);
});
};
btnClick(){
this.myfollow();
if(this.state.btnText === 'Follow'){
this.setState({
btnText:'Following'
})
} else{
this.setState({
btnText: 'Follow'
})
}
if(this.state.className === 'follow-button'){
this.setState({
className: 'following-button'
})
}
else{
this.setState({
className: 'follow-button'
})
}
}
render(){
return (
<div className="followdoe">
<button onClick={this.btnClick.bind(this)} className={this.state.className}>
<p>{this.state.btnText}</p>
</button>
</div>
);
}
}
if (document.getElementById('profile')) {
var data = document.getElementById('profile').getAttribute('data');
ReactDOM.render(<Example data={data} />, document.getElementById('profile'));
}
Profile.blade.php
<div id="profile" data='{{ $user->id }}'></div>