簡體   English   中英

React Redux表單2使用onSubmit和redirect提交

[英]React Redux form 2 submits with onSubmit and redirect

我正在嘗試用天氣和污染來改進應用程序。 主要的想法是有2個提交按鈕,重定向到其他網址。 我已經嘗試了一些選項,最后你看到的是關於制作2個onClick函數,但是我無法將數據傳遞給onFormSubmit函數。

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchWeather} from '../actions/index';
import { Link } from 'react-router';
import { reduxForm } from 'redux-form';

class SearchBar extends Component{
    constructor(props){
        super(props);

        this.state = {term:''};

        this.onInputChange= this.onInputChange.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
    }
static contextTypes = {
    router: React.PropTypes.object
  };

onInputChange(event){

    this.setState({term : event.target.value});
};




onFormSubmit(event){
    event.preventDefault();

if (this.numberButton == 1){
return (this.props.fetchWeather(this.state.term)
    .then(() => {
     this.context.router.push('/')}));
} else if (this.numberButton == 2){

} else {
    return console.log('Went wrong');
}



    this.setState({term:''});

};


    render(){
        return (
            <div>
            <form 
          onSubmit={this.onFormSubmit} 
            className="input-group">
                <input 
                placeholder="Put here a US city name"
                className="form-control"
                value={this.state.term}
                onChange={this.onInputChange}
                 />
                <span className="input-group-btn" role="group">
                        <button type="submit" name="button1" value="Weather" className="btn btn-secondary btn-success" onClick={ () => a=1} >Weather</button>
                        <button type="submit" name="button2" value="Polution" className="btn btn-secondary btn-info" onClick={() =>  a =2} >Polution</button>
                    </span>

                </form>

                </div>
        )
    }

}

function mapDispatchToProps(dispatch){
    return bindActionCreators({fetchWeather}, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchBar);  

有兩種不同的方法可以解決這個問題:

1)在每個按鈕上放置一個id(例如'weather-button'),然后檢查e.target.id ==='weather-button'而不是this.numberButton == 1.我沒有看到this.numberButton聲明在任何地方,所以這種情況永遠不會成真。

2)完全刪除表單包裝,並為每個按鈕提供不同的句柄。

handleWeatherClick = e => { ... }
handlePollutionClick = e => { ... }

...

<span className="input-group-btn" role="group">
    <button className="btn btn-secondary btn-success" onClick={this.handleWeatherClick}>
        Weather
    </button>
    <button className="btn btn-secondary btn-info" onClick={this.handlePollutionClick}>
        Pollution
    </button>
</span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM