我正在尝试将id
传递的getUsers()
作为prop
传递给子组件。
App.jsx
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import axios from 'axios';
import About from './components/About';
import NavBar from './components/NavBar';
import Form from './components/forms/Form';
import Logout from './components/Logout';
import UserStatus from './components/UserStatus';
import Seeds from './components/Seeds';
import Message from './components/Message';
class App extends Component {
constructor() {
super();
this.state = {
users: [],
title: 'Project',
isAuthenticated: false,
messageName: null,
messageType: null,
restaurant: '',
email: '',
id: '',
username: '',
active: '',
admin: '',
};
this.logoutUser = this.logoutUser.bind(this);
this.loginUser = this.loginUser.bind(this);
this.createMessage = this.createMessage.bind(this);
this.removeMessage = this.removeMessage.bind(this);
this.userStatus = this.userStatus.bind(this);
};
componentWillMount() {
if (window.localStorage.getItem('authToken')) {
this.setState({ isAuthenticated: true });
};
};
componentDidMount() {
this.getUsers();
this.userStatus();
};
getUsers() {
axios.get(`${process.env.REACT_APP_WEB_SERVICE_URL}/users`)
.then((res) => { this.setState({ users: res.data.data.users }); })
.catch((err) => { });
};
logoutUser() {
window.localStorage.clear();
this.setState({ isAuthenticated: false });
};
loginUser(token) {
window.localStorage.setItem('authToken', token);
this.setState({ isAuthenticated: true });
this.getUsers();
this.createMessage('Welcome', 'success');
};
userStatus(event) {
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/auth/status`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data)
console.log(res.data.data)
this.setState({
restaurant: res.data.data.restaurant,
email: res.data.data.email,
id: res.data.data.id,
username: res.data.data.username,
active: String(res.data.data.active),
admin: String(res.data.data.admin),
})
})
.catch((error) => { console.log(error); });
};
createMessage(name='Sanity Check', type='success') {
this.setState({
messageName: name,
messageType: type
});
setTimeout(() => {
this.removeMessage();
}, 3000);
};
removeMessage() {
this.setState({
messageName: null,
messageType: null
});
};
render() {
return (
<div>
<NavBar
title={this.state.title}
isAuthenticated={this.state.isAuthenticated}
/>
<section className="section">
<div className="container">
{this.state.messageName && this.state.messageType &&
<Message
messageName={this.state.messageName}
messageType={this.state.messageType}
removeMessage={this.removeMessage}
/>
}
<div className="columns">
<div className="column is-half">
<br/>
<Switch>
<Route exact path='/' render={() => (
<SpotifyAuth
/>
)} />
<Route exact path='/about' component={About}/>
<Route exact path='/register' render={() => (
<Form
formType={'Register'}
isAuthenticated={this.state.isAuthenticated}
loginUser={this.loginUser}
createMessage={this.createMessage}
/>
)} />
<Route exact path='/login' render={() => (
<Form
formType={'Login'}
isAuthenticated={this.state.isAuthenticated}
loginUser={this.loginUser}
createMessage={this.createMessage}
/>
)} />
<Route exact path='/logout' render={() => (
<Logout
logoutUser={this.logoutUser}
isAuthenticated={this.state.isAuthenticated}
/>
)} />
<Route exact path='/status' render={() => (
<UserStatus
isAuthenticated={this.state.isAuthenticated}
/>
)} />
<Route exact path='/seeds' render={() => (
<Seeds
isAuthenticated={this.state.isAuthenticated}
userStatus={this.userStatus}
/>
)} />
</Switch>
</div>
</div>
</div>
</section>
</div>
)
}
};
export default App;
Seeds.jsx
import React, { Component } from 'react';
import axios from 'axios';
class Seeds extends Component{
constructor (props) {
super(props);
this.state = {
restaurant:'',
email: '',
id: '',
username: '',
active: '',
admin: '',
template:'',
formSeeds:{
type1:'',
type2:'',
type3:'',
},
formEditMenu:{
item:'',
item2:'',
item3:'',
}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmitSeeds = this.handleSubmitSeeds.bind(this);
this.handleSubmitItems = this.handleSubmitItems.bind(this);
};
componentDidMount() {
if (this.props.isAuthenticated) {
this.getSeeds();
}
};
getSeeds(event) {
const {userStatus} = this.props
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds/${userStatus.id}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
this.setState({
restaurant: res.data.data[0].restaurant,
id: res.data.data[0].id,
template: res.data.data[0].content
})
console.log(userStatus.id);
})
.catch((error) => { console.log(error); });
};
handleChange(event){
const objformSeeds = this.state.formSeeds;
objformSeeds[event.target.name] = event.target.value;
this.setState(objformSeeds);
const formEditMenu = this.state.formEditMenu;
formEditMenu[event.target.name] = event.target.value;
this.setState(formEditMenu);
}
handleSubmitSeeds(event) {
event.preventDefault();
const {userStatus} = this.props
const data = {
type1: this.state.formSeeds.type1,
type2: this.state.formSeeds.type2,
type3: this.state.formSeeds.type3,
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/handle_seeds/${userStatus.id}`;
axios.post(url, data)
.then((res) => {
console.log(data);
})
.catch((err) => {
});
};
handleSubmitCoffees(event) {
event.preventDefault();
const {userStatus} = this.props
const data = {
item: this.state.formEditMenu.item,
item2: this.state.formEditMenu.items2,
items3: this.state.formEditMenu.items3,
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/edit_menu/${userStatus.id}`;
axios.post(url, data)
.then((res) => {
console.log(data);
})
.catch((err) => {
});
};
render(){
var __html = this.state.template;
var template = { __html: __html };
return (
<div id="parent">
<div dangerouslySetInnerHTML={template}/>
<form>
<input type='text' name='name' onChange={this.handleChange}/><br/>
<button type="button" onClick={this.handleSubmitItems} />
</form>
</div>
);
}
}
export default Seeds;
但是我得到的是userStatus undefined
。
XHR failed loading: GET "http://localhost/seeds/undefined".
console.log(userStatus):
userStatus(event) {
const options = {
url: "".concat("http://localhost", "/auth/status"),
method: 'get',
headers: {
'Content-Type': 'application/json',
Authoriza…
我想念什么?
答案 0 :(得分:0)
我建议您仅传递id,因为您使用this.userStatus是函数
userStatus={this.userStatus}
您需要更改为
userStatus={this.state.id}