我的Login.js
文件越来越大,所以我决定在单独的文件LoginForm.js
中创建一个可重用的组件。但是,在我将之前的代码从Login.js
提取到LoginForm.js
后,我的一个道具未定义,我不明白为什么。
未定义的道具: this.props.token
我导入了所有模块并比较了代码,一切似乎都是正确的。
在Login.js
我有这个:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createToken } from '../../actions/tokenActions'
import LoginForm from './LoginForm'
// Styles
import Typography from 'material-ui/Typography'
import Card, { CardActions, CardContent } from 'material-ui/Card'
import Button from 'material-ui/Button'
import { CircularProgress } from 'material-ui/Progress'
import injectSheet from 'react-jss'
class Login extends Component {
constructor(props) {
super(props)
this.state = {}
}
onFormSubmit(e) {
e.preventDefault()
this.props.createToken(this.state)
}
render() {
const progressBar = this.props.token.pending
? <CircularProgress className={this.props.progress} />
: ''
return (
<div className="box" style={{ margin: '100px auto', width: '300px' }}>
{progressBar}
<form
onSubmit={this.onFormSubmit.bind(this)}
style={{ display: this.props.token.pendling ? 'none' : 'block' }}
>
<LoginForm />
</form>
</div>
)
}
}
const mapState = state => {
return {
token: state.token
}
}
const mapDispatch = (dispatch, props) => ({
createToken: data => dispatch(createToken(data))
})
export default connect(mapState, mapDispatch)(Login)
在我的另一个档案中,LoginForm.js
我有这个:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createToken } from '../../actions/tokenActions'
//Styles
import Card, { CardActions, CardContent } from 'material-ui/Card'
import Button from 'material-ui/Button'
import Typography from 'material-ui/Typography'
export default class LoginForm extends Component {
constructor(props) {
super(props)
this.state = {}
}
onFormSubmit(e) {
e.preventDefault()
this.props.createToken(this.state)
}
render() {
console.log(this.props.token)
return (
<Card>
<CardContent>
<Typography
style={{
fontSize: '40px',
fontWeight: '300',
color: '#636363',
marginBottom: '20px'
}}
type="subheading"
gutterBottom
align="center"
>
Logga In
</Typography>
<input
type="text"
placeholder="Email"
onChange={e => this.setState({ email: e.target.value })}
/>
<input
type="password"
placeholder="Lösenord"
onChange={e => this.setState({ password: e.target.value })}
/>
<Button
raised
color="primary"
onClick={this.onFormSubmit.bind(this)}
className="text-center"
>
Skicka
</Button>
{this.props.token.rejected
? 'Felaktigt användarnamn eller lösenord'
: ''}
</CardContent>
</Card>
)
}
}
我敢打赌,这是一个非常基本的问题,但我没有别的问题比这里好。我非常感谢所有的帮助!
答案 0 :(得分:1)
<LoginForm />
不提供任何道具。
this.props
将不会被定义:<LoginForm token={this.props.token} />
道具如果你没有明确地写它就不会被传递,你可以逐个编写它们但你也可以输入这个:<LoginForm {...this.props} />