前后端数据通信之FromData

49次阅读

共计 3320 个字符,预计需要花费 9 分钟才能阅读完成。

所有向服务器提交的 HTTP 数据,其实都是一个表单

FromData 是一种容器,用于模拟表单,向服务器提交数据,有两种使用方法

  • 创建空白 FromData 对象,然后向其中添加数据
  • 将 <from> 标签直接转化为一个 FromData 对象

使用 FromData

注册一个用户:

async register(uName,uPwd){let fromData = new FormData();
    fromData.append('name',uName);
    fromData.append('pwd',uPwd);
    try {
      let res = await fetch('/api/adduser',{
        method:'POST',
        body:fromData
      })
  
      const {ok,err} = await res.json();
      if(ok){console.log('add user ok!')
      }else{console.log('add user fail!');
      }
    } catch (error) {console.log('error:',error)
    }
  }
  

上面的代码就简单介绍了 FromData 的第一种用法 (创建对象的方式),接下来针对 fetch 进行下简单的封装

封装 fetch

fetch.js

const BASEURL="http://localhost:3000/api"

export default async function(url,options){
    try {const res = await fetch(url,options);
        const {ok,error,data} = await res.json();
        if(ok){return data}else{console.error(error);
            throw new Error(error)
        }
    } catch (error) {throw error}
}

FromData+React+React-Redux 结合使用

注册用户,并显示用户列表:

Reg.js

import React, {Component} from 'react';
import {connect} from 'react-redux'
import fetchJson from '../fetch'
import {from} from '_rxjs@6.5.2@rxjs';
class Reg extends Component {async submit(){// let fromData = new FormData();
        // fromData.append('name',this.refs.name.value);
        // fromData.append('pwd',this.refs.password.value);
        let fromData = new FormData(this.refs.from1);
        let data = await fetchJson('/api/adduser',{
            method:'POST',
            body:fromData
        })
        this.props.add_user({
            name:this.refs.name.value,
            pwd:this.refs.password.value
        })
        this.refs.name.value = "";
        this.refs.password.value = "";
    }

    render() {
        return (
            <div>
                <from ref="from1">
                    用户:<input type="text" name="name" ref="name"/><br/>
                    密码:<input type="password" name="password" ref="password"/><br/>
                    <input type="button" value="注册" onClick={this.submit.bind(this)}/>
                </from>
            </div>
        );
    }   
}

export default connect((state,props) => Object.assign({},props,state),{add_user(user){
        return{
            type:'ADD_USERS',
            user
        }
    }
})(Reg);

Table.js

import React, {Component} from 'react';
import {connect} from 'react-redux'
import fetchJson from '../fetch'

class Table extends Component {constructor(){super();
    }
    async componentDidMount(){const data = await fetchJson('/api/userlist');
        this.props.init_users(data)
    }
    render() {
        return (
            <div>
                <table border="1" width="100%">
                  <thead>
                    <tr>
                        <th> 用户名 </th>
                        <th> 密码 </th>
                    </tr>
                  </thead>
                  <tbody>
                     {this.props.users.map(({...item},index)=>(<tr key={index}>
                                <td>{name}</td>
                                <td>{pwd}</td>
                            </tr>
                         ))
                     }
                  </tbody>  
                </table>
            </div>
        );
    }
}

export default connect((state,props) => Object.assign({},props,state),{init_users(users){
        return{
            type:'SET_USERS',
            users
        }
    }
})(Table);

App.js

import React, {Component} from 'react';
import Table from './components/Table'
import Reg from './components/Reg'
class App extends Component {render() {
    return (
      <div>
        <Reg/>
        <Table/>
      </div>
    );
  }
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {async} from 'q';
import {Provider} from 'react-redux'
import store from './store'
ReactDOM.render(<Provider store={store}>
       <App />     
    </Provider>, 
    document.getElementById('root')
    );

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

store.js

import {createStore,combineReducers} from 'redux'

function users(state=[],action){switch(action.type){
        case 'SET_USERS':
            return action.users
        case 'ADD_USERS':
            return [
                ...state,
                action.user
            ]

        default:
            return state
    }
}

export default createStore(combineReducers({users}))

总结:

  • 使用 FromData 创建对象,并 append 的方式适合小量数据,并不易变的操作
  • 使用 from 表单直接转换成 FromData 的方式更加灵活,可控

正文完
 0