首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在react js中根据API响应显示消息。

在react js中根据API响应显示消息。
EN

Stack Overflow用户
提问于 2017-05-26 05:14:46
回答 2查看 10.3K关注 0票数 1

我已经安装了使用-创建-反应-应用。我使用onSubmit()函数提交表单。在从LoginRegister.js组件提交表单时,下面是我的LoginRegister.js文件代码-

代码语言:javascript
运行
复制
import React from 'react'; 
import DefaultLayout from '../Layout/DefaultLayout';
import PropTypes from 'prop-types';
import { connect } from 'react-redux'; 
import { userSignupRequest } from '../actions/signupActions';



class LoginRegister extends React.Component {
    constructor(props) {
    super(props);
        this.state = {first_name: '',last_name: '',email:'',password:'',c_password:'', phone_no:'',user_role:2, errmsg:''};
        //this.state = {about: ''};

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleInputChange(event) {
        this.setState({ [event.target.name]: event.target.value});
      }

    handleSubmit(event) {
        event.preventDefault();
        this.props.userSignupRequest(this.state);
    }   

    render(){
        return (
            <DefaultLayout>
                <section id="page-title">

                    <div className="container clearfix">
                        <h1>My Account</h1>
                        <ol className="breadcrumb">
                            <li><a href="/">Home</a></li>
                            <li><a href="/">Pages</a></li>
                            <li className="active">Login</li>
                        </ol>
                    </div>

                </section>

                <section id="content">

                    <div className="content-wrap">

                        <div className="container clearfix">
                            <div className="col_two_third col_last nobottommargin">


                                <h3>Dont have an Account? Register Now.</h3>

                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, vel odio non dicta provident sint ex autem mollitia dolorem illum repellat ipsum aliquid illo similique sapiente fugiat minus ratione.</p>
                                <p id="msg">{this.state.errmsg}</p>
                                <form id="register-form" name="register-form" className="nobottommargin" method="post" onSubmit={this.handleSubmit}>

                                    <div className="col_half">
                                        <label htmlFor="register-form-name">First Name:</label>
                                        <input type="text" id="register-form-firstname" name="first_name" value={this.state.first_name} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-email">Last name:</label>
                                        <input type="text" id="register-form-lastname" name="last_name" value={this.state.last_name} className="form-control" onChange={this.handleInputChange} required={true} />
                                    </div>

                                    <div className="clear"></div>

                                    <div className="col_half">
                                        <label htmlFor="register-form-email">Email Address:</label>
                                        <input type="text" id="register-form-email" name="email" value={this.state.email} className="form-control" onChange={this.handleInputChange} required={true} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-repassword">Phone no.:</label>
                                        <input type="text" id="register-form-phone" name="phone_no" value={this.state.phone_no} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="clear"></div>

                                    <div className="col_half">
                                        <label htmlFor="register-form-password">Choose Password:</label>
                                        <input type="password" id="register-form-password" name="password" value={this.state.password} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-repassword">Re-enter Password:</label>
                                        <input type="password" id="register-form-repassword" name="c_password" value={this.state.c_password} className="form-control" onChange={this.handleInputChange} />
                                    </div>
                                    <input type="hidden" name="user_role" value={this.state.user_role} className="form-control" />  
                                    <div className="clear"></div>

                                    <div className="col_full nobottommargin">
                                        <button className="button button-3d button-black nomargin" id="reg-submit" name="register-form-submit" value="register">Register Now</button>
                                    </div>

                                </form>

                            </div>

                        </div>

                    </div>
                </section>

            </DefaultLayout>
        )
    }
}

LoginRegister.propTypes = {
    userSignupRequest: PropTypes.func.isRequired    
}

export default connect((state) => { return{} }, {userSignupRequest} ) (LoginRegister); 

而action/signupActions文件的代码如下:调用API并使用Reducer处理响应-

代码语言:javascript
运行
复制
import axios from 'axios'; 

export function userSignupRequest(userData){
        return dispatch => {
            dispatch({"type":"CALL_START"});
            axios.post('../user/register', userData).then(response => {
              dispatch({"type":"RECEIVE_RESPONSE", "payload":response.data});
            }).catch(error => {
                dispatch({"type":"RECEIVE_ERROR", "payload":error});
            });
        }

    }

Reducer.js具有以下代码-

代码语言:javascript
运行
复制
const reducer = (state={}, action) => {
    switch(action.type){
        case "CALL_START" :{
            alert("Hi1");
            return {}
            break;  
        }
        case "RECEIVE_RESPONSE" : {
            //return {...state, data:action.payload}
            alert("Hi2");
            return {data:action.payload}
            break;
        }
        case "RECEIVE_ERROR" : {
            alert("Hi3");
            alert(JSON.stringify(action.payload));
            return {data:action.payload}
            break;
        }

    }   

}   

export default reducer;

API正在调用,我正在正确地获得响应,但在这里,我不知道如何在我的“LoginRegister.js”组件上显示基于响应的成功/错误消息。

请帮我解决这个问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-26 06:37:33

所以我建议你做些改变

  1. 当您使用connect时,您可能应该通过不提供要连接的第二个参数来连接要分派的动作,或者直接在组件中调用它。
  2. 让状态在你的组件中。为此,您可以使用mapStateToProps
  3. 您可能希望在注册表上显示一条正确的消息,您可以从userSignupRequest操作中这样做。

将代码更改为以下代码

UserSignUpRequest动作

代码语言:javascript
运行
复制
import axios from 'axios'; 

export function userSignupRequest(userData){
        return dispatch => {
            dispatch({"type":"CALL_START"});
            axios.post('../user/register', userData).then(response => {
              dispatch({"type":"RECEIVE_RESPONSE", "payload":"Successfully Registered"});
            }).catch(error => {
                dispatch({"type":"RECEIVE_ERROR", "payload":"Error Registering " +  JSON.stringify(error)});
            });
        }

    }

LoginRegister

代码语言:javascript
运行
复制
import {bindActionCreators} form 'redux';
class LoginRegister extends React.Component {
    constructor(props) {
    super(props);
        this.state = {first_name: '',last_name: '',email:'',password:'',c_password:'', phone_no:'',user_role:2, errmsg:''};
        //this.state = {about: ''};

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleInputChange(event) {
        this.setState({ [event.target.name]: event.target.value});
      }

    handleSubmit(event) {
        event.preventDefault();
        this.props.userSignupRequest({...this.state})
    }   

    render(){
        console.log(this.props.registerMessage)
        return (
            <DefaultLayout>
                <section id="page-title">

                    <div className="container clearfix">
                        <h1>My Account</h1>
                        <ol className="breadcrumb">
                            <li><a href="/">Home</a></li>
                            <li><a href="/">Pages</a></li>
                            <li className="active">Login</li>
                        </ol>
                    </div>

                </section>

                <section id="content">

                    <div className="content-wrap">

                        <div className="container clearfix">
                            <div className="col_two_third col_last nobottommargin">


                                <h3>Dont have an Account? Register Now.</h3>

                                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde, vel odio non dicta provident sint ex autem mollitia dolorem illum repellat ipsum aliquid illo similique sapiente fugiat minus ratione.</p>
                                <p id="msg">{this.props.registerMessage}</p>
                                <form id="register-form" name="register-form" className="nobottommargin" method="post" onSubmit={this.handleSubmit}>

                                    <div className="col_half">
                                        <label htmlFor="register-form-name">First Name:</label>
                                        <input type="text" id="register-form-firstname" name="first_name" value={this.state.first_name} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-email">Last name:</label>
                                        <input type="text" id="register-form-lastname" name="last_name" value={this.state.last_name} className="form-control" onChange={this.handleInputChange} required={true} />
                                    </div>

                                    <div className="clear"></div>

                                    <div className="col_half">
                                        <label htmlFor="register-form-email">Email Address:</label>
                                        <input type="text" id="register-form-email" name="email" value={this.state.email} className="form-control" onChange={this.handleInputChange} required={true} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-repassword">Phone no.:</label>
                                        <input type="text" id="register-form-phone" name="phone_no" value={this.state.phone_no} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="clear"></div>

                                    <div className="col_half">
                                        <label htmlFor="register-form-password">Choose Password:</label>
                                        <input type="password" id="register-form-password" name="password" value={this.state.password} className="form-control" onChange={this.handleInputChange} />
                                    </div>

                                    <div className="col_half col_last">
                                        <label htmlFor="register-form-repassword">Re-enter Password:</label>
                                        <input type="password" id="register-form-repassword" name="c_password" value={this.state.c_password} className="form-control" onChange={this.handleInputChange} />
                                    </div>
                                    <input type="hidden" name="user_role" value={this.state.user_role} className="form-control" />  
                                    <div className="clear"></div>

                                    <div className="col_full nobottommargin">
                                        <button className="button button-3d button-black nomargin" id="reg-submit" name="register-form-submit" value="register">Register Now</button>
                                    </div>

                                </form>

                            </div>

                        </div>

                    </div>
                </section>

            </DefaultLayout>
        )
    }
}


function mapStateToProps(state){
      return { 
         registerMessage: state.data
      }
}
function mapDispatchToProps(dispatch) {
      return bindActionCreators({userSignupRequest: userSignupRequest}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps ) (LoginRegister);

减速器

代码语言:javascript
运行
复制
const initialState = { 
    data: '',
    status: ''
}
const reducer = (state=initialState, action) => {
switch(action.type){
case "CALL_START" :{
alert("Hi1");
return {}
break; 
}
case "RECEIVE_RESPONSE" : {
//return {...state, data:action.payload}
return {...state, data:action.payload}
break;
}
case "RECEIVE_ERROR" : {
alert(JSON.stringify(action.payload));
return { ...state, data:action.payload}
break;
}
default: {
return state
}
} 

} 

export default reducer;
票数 3
EN

Stack Overflow用户

发布于 2017-05-26 05:18:22

但在这里,我不知道如何在我的“LoginRegister.js”组件上显示基于响应的成功/错误消息

使用@connect订阅状态。

更多

  • http://redux.js.org/docs/basics/UsageWithReact.html
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44194086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档