简体   繁体   English

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

[英]Pass data from one page to another page

I am new in react,redux.我是反应新手,redux。 When I click on submit button.当我点击提交按钮时。 I want to add information which should be displayed on another page like name and mobile no etc. don't know how should i do?我想添加应该显示在另一个页面上的信息,例如姓名和手机号等。不知道该怎么办? Please help here is my code.请帮助这里是我的代码。

App.js应用程序.js

Here I mentioned my all routes在这里我提到了我的所有路线

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添加联系人.js

here is my add contact form where i add my information这是我的添加联系表,我在其中添加我的信息

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 here is my contact list their i want to add my contact info ContactList.js 这是我的联系人列表,我想添加我的联系信息

import React from 'react';

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

If you are using redux:如果您使用的是 redux:

  1. you have to do is create a reducer that holds your state and reacts to your addContact method.您要做的就是创建一个减速器来保存您的 state 并对您的 addContact 方法做出反应。
  2. you need to connect your ContactList to your state and return the data you need ("contacts")您需要将您的联系人列表连接到您的 state 并返回您需要的数据(“联系人”)
  3. Make yure that your addContact action is adding the new contact to "contacts" and only call addAction when all your data is added.确保您的 addContact 操作正在将新联系人添加到“联系人”,并且仅在添加所有数据后才调用 addAction。 I dont understand why you have submits for each field instead of just submitting it when both fields are filled?我不明白您为什么要为每个字段提交而不是在两个字段都填写时才提交?

You ContactList should look something like this:您的 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);

Alternatively I can recommend a global-hook lib that will make such things much easier.或者,我可以推荐一个全局钩子库,它会让这些事情变得更容易。

npm install --save rx-global

Then in you component you can use it like this:然后在您的组件中,您可以像这样使用它:

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>
)
};

And in your ContactList you can use the state like this:在您的 ContactList 中,您可以像这样使用 state:

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>
    )
}

I hope this helps我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM