问题似乎是当在handleOnSubmit
中调用this.state
时,它确实返回了所需的输入。
但是,一旦this.state
用作this.props.addPhone(this.state)
中的参数,它就会返回{type: "CREATE_PHONE", phone: undefined}
。
我相信的代码与我的问题相关,从一个动作开始:
addPhone
动作:
export const addPhone = phone => {
return {
type: 'CREATE_PHONE',
phone
}
}
电话减速器(此处操作为undefined
(:
const phoneReducer = (state = {phones: [], loading: false}, action) => {
switch (action.type) {
case 'CREATE_PHONE':
const phone = {
id: uuid(),
make: action.make,
model: action.model,
price: action.price
}
return {...state, phones: [...state.phones, phone]}
default:
return state;
}
}
export default phoneReducer
现在,电话形式:
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { fetchPhones } from '../actions/phoneActions';
import { addPhone } from '../actions/phoneActions';
import PhoneList from './PhoneList';
class App extends Component {
state = {
make: '',
model: '',
price: 0
}
handleOnChange = event => {
this.setState({
[event.target.name]: event.target.value
});
}
handleOnSubmit = event => {
event.preventDefault();
this.props.addPhone(this.state)
this.setState({
make: '',
model: '',
price: 0
});
}
componentDidMount() {
this.props.fetchPhones()
}
render() {
return (
<div>
<h2>WELCOME TO OUR STORE</h2>
<div>
<h4>ADD A NEW PHONE</h4>
<div>
<form onSubmit={this.handleOnSubmit} >
<input
name="make"
type="text"
value={this.state.make}
onChange={this.handleOnChange} /><br/>
<input
name="model"
type="text"
value={this.state.model}
onChange={this.handleOnChange} /><br/>
<input
name="price"
type="number"
value={this.state.price}
onChange={this.handleOnChange} /><br/><br/>
<input type="submit" />
</form>
</div>
</div>
<div>
<h4>CLICK HERE TO REMOVE PHONES</h4>
<button> click here </button>
</div>
<div id="showPhones">
<h4>SEE BELOW OUR PHONE OFFER</h4>
<PhoneList phones={this.props.phones} loading={this.props.loading}/>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
phones: state.phones,
loading: state.loading
}
}
const dispatchToProps = (dispatch) => {
return {
addPhone: () => dispatch(addPhone()),
fetchPhones: () => dispatch(fetchPhones())
}
}
export default connect (mapStateToProps, dispatchToProps)(App)
this.props.addPhone(this.state)
正在返回:{type: "CREATE_PHONE", phone: undefined}
,这似乎是一个错误?
如果这个问题缺乏专业的代码编写,我真的很抱歉,但我只是编码和starkoverflow的初学者。
在我深入研究之前,我注意到
addPhone: () => dispatch(addPhone()),
你至少需要在这次通话中通过电话,例如
addPhone: phone => dispatch(addPhone(phone))
调度如何知道要添加什么:(