簡體   English   中英

使用React Redux提交FORM數據的最佳方式?

[英]Best way to submit FORM data with React Redux?

我對這個簡單的問題感到很難過! 我想簡單地獲取表單數據,驗證它,提交它並向Express API提交發布請求。 但在此之前,我認為我沒有徹底了解如何實現這一目標。 我看了看這個問題, 這些和一堆人,但我不知道這是最好的辦法。

這是我假設將采取的方式:

我為注冊頁面創建了一個React組件。 (簡化用於演示)

class SignupForm extends Component {
    constructor(props){
        super(props);
        this.onSubmit = this.onSubmit.bind(this);
    }
    onSubmit(val){
        debugger;
    }
    render(){
        return (
            <form onSUbmit={ (e)=> this.onSubmit(e) }>
                <input type="text" />
                <label></label>
                <button type="submit">Submit</button>
            </form>
        )
    }
}

單擊按鈕時,將觸發OnSubmit()函數,在該函數中將傳遞JSON數據。

{
   "name": "Kanye",
   "surname": "West",
   "email":"yeezy@goodmusic.com",
   "password":"notsurehowthiswillwork"
}

我可以在哪里觸發我的動作SignupAction() ,它將對我的API進行AJAX調用,然后更新我的reducer。

當使用像react-redux-formredux- forms這樣的庫時,混淆成倍增加。 我只想簡單地使用一個模型或namesurname emailpassword ,但我覺得這些庫一旦開始擁有自己的reducer,就會過度設計:

const store = createStore(combineForms({
   user: initialUser,
}));

我的其他選擇是:

class SignupForm extends Component {

    constructor(props){
        super(props);
        this.state.form = {
            name : '',
            surname: '',
            email: '',
            password: ''
        }
    }
    onSubmit(e){
        e.preventDefault();
        this.props.SignupAction(this.state.form);
        // then reset the state agian to '' 
    }
}

但是 ,我的問題是......這會影響表現,如果是這樣的話為什么?

處理表單非常簡單:

 class UserInfo extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); const formData = {}; for (const field in this.refs) { formData[field] = this.refs[field].value; } console.log('-->', formData); } render() { return ( <div> <form onSubmit={this.handleSubmit}> <input ref="phone" className="phone" type='tel' name="phone"/> <input ref="email" className="email" type='tel' name="email"/> <input type="submit" value="Submit"/> </form> </div> ); } } export default UserInfo; 

我建議使用redux-form 它為您提供以下選項:

  1. 輸入驗證
  2. 輸入上的不同類型包括日期和文件上載
  3. 提供一個onSubmit方法,在驗證成功后調用該方法(這是您調度操作以調用API和更新狀態的點)

但如果仍然不想使用(我強烈建議使用它),你可以做的是在表單提交只是驗證你的數據並在你的容器中發送一個動作。 因此,將您的數據作為參數從組件傳遞到容器,您可以在其中發送操作調用post / put API(以redux形式,您不需要傳遞任何內容,您可以直接從商店中讀取)。

    onSubmit(val){
        debugger;
    }
    render(){
        const { onSubmit } = this.props //pass onSubmit from 
        return (
            <form onSubmit={ (e)=> {onSubmit} ) }>
                <input type="text" />
                <label></label>
                <button type="submit">Submit</button>
            </form>
        )
    }
}

容器:

mapDispatchToProps(dispatch){
   return {
    onSubmit => {
     //dispatch action
     }
  }

暫無
暫無

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

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