handleSubmitSearch函数调用一个thunk(调用fetch调用)以呈现在新页面上。此功能在没有路由器的情况下有效,但使用路由器时,甚至不会调用handleSubmitSearch(控制台日志不会触发,提取调用也不会)。我还尝试过使用多种生命周期方法,例如componenetWillUpdate,componentShouldUpdate,componentwillreceiveprops等。我还尝试安装了连接反应路由器npm模块,该模块无法解决问题。
我已经在这个问题上搜索了好几个小时,但似乎无法弄清楚为什么我的修复程序都无法正常工作。
export class SearchDirections extends React {
constructor() {
super()
this.state = {
origin: '',
departure: '',
mode: ''
}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
};
handleRadioChange = (e) => {
this.setState({
mode: e.target.value
});
}
handleSubmitSearch = async (e) => {
e.preventDefault();
console.log('test')
await this.props.getNewDirections(this.state.origin, this.state.departure, this.state.mode)
if(this.props.direction) {
let startCoordinates = this.props.directions.routes[0].legs[0].start_location
let endCoordinates = this.props.directions.routes[0].legs[0].end_location
await this.props.displayWeatherStart(startCoordinates)
}
};
render() {
return (
<form
onSubmit={this.handleSubmitSearch}>
<input
placeholder='enter origin'
className='origin'
name='origin'
value={this.state.origin}
onChange={(e) => this.handleChange(e)}
/>
<input
placeholder='enter departure'
className='departure'
name='departure'
value={this.state.departure}
onChange={(e) => this.handleChange(e)}
/>
<Link to='/directions'>
<button className='submit-btn'>submit</button>
</Link>
<ul>
<li>
<label>
<input
className='radio'
type='checkbox'
value='transit'
name='radio'
checked={this.state.mode === 'transit'}
onChange={this.handleRadioChange}
/>
transit
</label>
</li>
<li>
<label>
<input
className='radio'
type='checkbox'
value='walking'
name='radio'
checked={this.state.mode === 'walking'}
onChange={this.handleRadioChange}
/>
walking
</label>
</li>
<li>
<label>
<input
className='radio'
type='checkbox'
value='bicycling'
name='radio'
checked={this.state.mode === 'bicycling'}
onChange={this.handleRadioChange}
/>
bicycling
</label>
</li>
<li>
<label>
<input
className='radio'
type='checkbox'
value='driving'
name='radio'
checked={this.state.mode === 'driving'}
onChange={this.handleRadioChange}
/>
driving
</label>
</li>
</ul>
</form>
)
}
}
export const mapStateToProps = (state) => ({
directions: state.directions,
startWeather: state.startWeather,
isLoading: state.isLoading
});
export const mapDispatchToProps = (dispatch) => ({
getNewDirections: (origin, departure, mode) => dispatch(getCurrentDirections(origin, departure, mode,)),
displayWeatherStart: (city) => dispatch(getCurrentWeather(city)),
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SearchDirections));
答案 0 :(得分:0)
以这种方式设置它可能会成功,因为您需要将withRouter
的(HOC)功能传递给组件:
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(SearchDirections));
答案 1 :(得分:0)
我建议您再次尝试使用connected-react-router npm模块。除了此模块之外,请尝试使用npm Redux Form模块来处理表单。 Redux Form具有装饰器,可让您将表单组件连接到Redux。这个称为reduxForm的装饰器具有许多属性,包括 onSubmit ,我认为您需要在使用路由器时呈现一个新页面, onSubmitSuccess 。这是一篇有关使用Redux Form的好文章。