将数据从一页传递到另一页

时间:2020-07-07 07:20:49

标签: javascript react-redux react-hooks react-router-dom

redux我是React的新手。当我点击提交按钮。我想添加应该在另一页上显示的信息 例如姓名和手机号码等。 不知道该怎么办?请帮忙 这是我的代码。

App.js

在这里我提到了我的所有路线

import React from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Switch,BrowserRouter as Router,Route,} from 'react-router-dom'

//importing components
import AddContact from './component/addContact';
import Save from './forms/save';
import ContactList from './forms/contactList';

//redux
import {Provider} from 'react-redux';
import store from './store';


function App() {
  return (
   <Provider store={store}>
     <Router>
       <Route exact path='/' component={Save}></Route>
       <Route exact path ='/add' component={AddContact}></Route>
       <Route exact path = '/contact' component={ContactList}></Route>
     </Router>
   </Provider>
  );
}

export default App;

Addcontacts.js

这是我的添加联系人表格,我可以在其中添加我的信息

import React, { useState, useEffect, useReducer } from 'react';

import { v4 } from 'uuid';

//redux
import { connect } from 'react-redux';
import { addContact } from '../action/contact';
import { Link } from 'react-router-dom';

const AddContact = () => {

    const [name, setName] = useState('');
    const [number, setNumber] = useState('');

    const handleNameSubmit = e => {

        if (name === '') {
            return alert('please add name')
        }
        const Contact = {
            name,
            id: v4()
        }

        addContact(Contact);

        setName('')


    }

    const handleNumberSubmit = e => {

        if (number === '') {
            return alert('please add number')
        }

        const Contact = {
            number,
            id: v4()
        }

        addContact(Contact);

        setNumber('')

    }


    return (
        <form>
            <h1 style={{ textAlign: 'center' }}>Add Contact</h1>
            <div className='container'>
                <div className='form-group'>
                    <label style={{ float: 'left' }}>Name</label>
                    <input type="text"
                        className="form-control"
                        id="exampleInputEmail1"
                        aria-describedby="emailHelp"
                        placeholder='Enter Your Name'
                        required
                        value={name}
                        onChange={e => setName(e.target.value)} />
                </div>
                <div className='form-group'>
                    <label style={{ float: 'left' }}>Mobile No</label>
                    <input type="number"
                        className="form-control"
                        id="exampleInputMobile"
                        aria-describedby="emailHelp"
                        placeholder='Enter Your Mobile No'
                        required
                        value={number}
                        onChange={e => setNumber(e.target.value)} />
                </div>
                <div className='form-group'>
                    <label style={{ float: 'left' }}>Gender</label>
                    <select className='form-control'>
                        <option>Male</option>
                        <option>Female</option>
                        <option>Other</option>
                    </select>
                </div>
                <Link to='/contact'>      <button className='btn btn-primary' id='btn1' onClick={() => {
                    handleNameSubmit();
                    handleNumberSubmit();
                }}>Submit</button></Link>
                <span><button className='btn btn-primary' id='btn2'>Cancle</button></span>
            </div>

        </form>
    )
}

const mapStateToProps = state => ({})

const mapDispatchToProps = dispatch => ({
    addContact: contact => {
        dispatch(addContact(contact));
    },
});



export default connect(mapStateToProps, mapDispatchToProps)(AddContact);

ContactList.js 这是我要添加我的联系信息的联系人列表

import React from 'react';

const ContactList = () => {
    return (
        <div>
            <h1>Hii</h1>
        </div>
    )
}
export default ContactList;

1 个答案:

答案 0 :(得分:0)

如果您使用的是redux:

  1. 您需要做的是创建一个可保存状态并对addContact方法做出反应的reducer。
  2. 您需要将ContactList连接到您的州,并返回所需的数据(“联系人”)
  3. 请确保您的addContact操作将新联系人添加到“联系人”,并且仅在添加所有数据时才调用addAction。我不明白为什么您要为每个字段都提交,而不仅仅是在两个字段都填写后才提交?

您的ContactList应该看起来像这样:

// deconstruct your properties from props
const ContactList = ({ contacts }) => {
    return (
        <ul>
          {contacts.map(({ name, email, number }) => (
             <li>
               <h1>Hii {name}</h1>
             </li>
        </ul>
    )
}
// deconstruct "contacts" from your global state object
const mapStateToProps = ({ contacts }) => ({
  contacts
});

const mapDispatchToProps = dispatch => ({});

export default connect(mapStateToProps, mapDispatchToProps)(ContactList);

或者,我可以推荐一个全局钩子库,它将使这些事情变得更加容易。

npm install --save rx-global

然后在组件中可以像这样使用它:

import { v4 } from 'uuid';
import { Link } from 'react-router-dom';
import { setGlobalState } from "rx-global";

const addContact = contact => updateGlobalState("contacts", state => [...state, contact]);

const AddContact = () => {
const [name, setName] = useState('');
const [number, setNumber] = useState('');

const handleSubmit = () => {
  addContact({ name, number });
  setName("");
  setNumber("");
};

return (
    <form>
        <h1 style={{ textAlign: 'center' }}>Add Contact</h1>
        <div className='container'>
            // ...your code...
            <Link to='/contact'>      
               <button className='btn btn-primary' id='btn1' onClick{handleSubmit}>
                 Submit
               </button>
            </Link>
            <span>
              <button className='btn btn-primary' id='btn2'>
                Cancle
              </button>
            </span>
        </div>

    </form>
)
};

在ContactList中,您可以使用如下状态:

import { useGlobalState } from "rx-global";

const ContactList = () => {
    const [contacts] = useGlobalState("contacts", []);
    return (
        <ul>
          {contacts.map(({ name, email, number }) => (
             <li>
               <h1>Hii {name}</h1>
             </li>
        </ul>
    )
}

我希望这会有所帮助