一、介绍

        本文将会基于react实现表单功能,包括表单提交和跳转错误处理动态表单元素动态内容加载。

二、使用教程

1.表单提交功能

export default class FormSubmit extends React.PureComponent{
    
    state = {
        name: ""
    }

    handleNameChange = evt => {
        this.setState({
            name: evt.target.value
        });

    }

    handleSubmit = evt => {
        evt.preventDefault(); // 阻止默认事件
        if (!this.state.name){
            this.setState({error: "Name is required"});
            return;
        }
        fetchUserList(this.state.name);        
    }
    
    const {userState, fetchUserList} = useFetchUserList();

    render(){
        return (
            <&gt;
            <form className = "comment-box" onSubmit = {this.handleSubmit}&gt;
                <div&gt;
                    <label&gt;Name:</label&gt; 
                    <input value = {this.state.name} onchange = {this.handleNameChange}/>
                </div>
                
                <div>
                    <button>Submit</button>
                </div>
            </form>
            {userState.data &amp;&amp; <ul>userState.data.map((user)=> <li>user.name</li>)</ul>}
            </>
        )    
    
    }


    

}

userservice.js

const initialState = {data:[], isLoading:false, error:null};

// reducer
function reducer(state, action){
    switch (action.type){
        case FETCH_USER_LIST_BEGIN:
            return (data:[action.res.data], isLoading: true, error:null);
        case FETCH_USER_LIST_SUCCESS:
            return (...state, isLoading: false, error:null);
        case FETCH_USER_LIST_ERROR:
            return (...state, isLoading: false, 
                    error:res.data.error);
    
    }
    
}

const [state, dispatch] = useReducer(reducer, initialState);

function fetchUserList(){

     dispatch({type: FETCH_USER_LIST_BEGIN});    
     
     const doRequest = axios.get("http://www.user.com/user/list");
     doRequest.then(
                res => {
                    dispatch({
                        type: FETCH_USER_LIST_BEGIN,
                        data: res.data
                    });
                },
                err => {
                    dispatch({
                        type: FETCH_USER_LIST_ERROR,
                        data: {error:err}
                        }
                    );
          
                }
            );
}


export default userFetchUserList = () => {state, fetchUserList}


2.动态表单元素 (TODO)

原文地址:https://blog.csdn.net/qq_37011724/article/details/134793153

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_42510.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注