簡體   English   中英

我如何使用帶有 redux 和 react.js 的按鈕將數據從一個組件傳遞到另一個組件?

[英]How can i pass the data from one Component to another using a button with redux and react.js?

我正在做一個計費列表項目......每當用戶點擊項目頁面中的一個按鈕時,該按鈕應該發送一個帶有 Fetched API 的隨機項目到第二頁,即計費頁面,它應該匹配並顯示信息!

在使用 Axios 獲取數據后,我設法將其保存到 Redux 商店....我嘗試使用 props 發送數據或顯示它但沒有任何效果,它返回一個錯誤提示 TypeError: Cannot read property 'props' of undefined ....? 我究竟做錯了什么 ?

我真的很感激一些反饋或任何對我有幫助的建議。 謝謝!

這是我的項目頁面代碼

    import React, { useEffect , useState} from 'react'
import { connect } from 'react-redux'
import { getItems } from '../store/actions/itemsActions';
import {  Link } from "react-router-dom";




function Items ({ getItems, items }) {

  useEffect(() => {
    getItems()
  }, [])

  


  function getRandomElt(arrayLenght) {
    return  items.sort(() => Math.random() - Math.random()).find(() => true);
  }




  function handleClick(){

    items &&
    items.items &&
     items.items.map(item => {
      <React.Fragment key={item.id}>
        <h4>{item.title}</h4>
      </React.Fragment>
    })

    
  }



return (
  
    

    <div>

      <div className="image" style={{ display: "flex",
          justifyContent: "center",
          alignItems: "center",}}>
        <img
        src="http://i.stack.imgur.com/yZlqh.png"
        alt=""
      />
        </div>
       
      


        <div className="button" style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
        }}>
         
          <div className="item-preview" >
            {
              items &&
              items.items &&
              items.items.map((item) => (
                <div key={item.id}>
                  <h2>{item.title}</h2>
                  <h2>{item.price}</h2>
                </div>

              ))
            } 
              {/* /${items.id} */}
          <Link onClick={handleClick}  to={`/bills`}
          ><button className="btn btn-primary">Analyse Receipt</button>
      
          </Link>

          </div>
     
        </div>
        
        
    </div>
  )
}

const mapStateToProps = state => {
  return {
    items: state.items
  }
}

const mapDispatchToProps = dispatch => {
  return {
    getItems: () => dispatch(getItems())
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Items)

這是我的計費頁面代碼

import React, { useState } from 'react';
import './Bill.css'
import { Link, useParams } from 'react-router-dom';
import { connect } from 'react-redux'
import { getItems } from '../store/actions/itemsActions';

function BillList ({ getItems ,items}){

  const [counter, setCounter] = useState(1)
  const incrementCounter = () => setCounter(counter + 1);
  let decrementCounter = () => setCounter(counter - 1);
  if(counter<=0) {
    decrementCounter = () => setCounter(1);
  }

  const { id } = useParams();
  let Total = 0


  // increase the item number 
  function ButtonIncrement(props) {
  
    return (
      <button style={{ marginLeft: '.1rem', textAlign: 'left'}} onClick={props.onClickFunc}>
      +
      </button>
    )
 }

//  will decrement the item number  

 function ButtonDecrement(props) {
  
  return (
    <button style={{ marginLeft: '.1rem',textAlign: 'left'}} onClick={props.onClickFunc}>
    -
    </button>
  )
}

// will display the current number 

function Display(props) {
  return (
    <label style={{ marginLeft: '.5rem'}} >{props.message}</label>
  )
}


 

    return(

      <div className='bills'>
       <h1>Product id: {id}</h1>

          <div className='title' style={{textAlign:'center', 
          justifyContent: "center",
          alignItems: "center",
          fontSize: 14,
        }}>
          <h1>Bakery</h1>
          <h1>Company Gbr</h1>
          <h1>Oranienburger Straße 120</h1>
          <h1>10119 Berlin</h1>
          </div>
          

          <div className="bills-container">
          <div>
      </div>
     
            {/* pass in the details  */}
            <div className="bill-number">
            {items &&
            items.items &&
             items.items.map(item => 
            <React.Fragment key={item.id}>
              <div className="bill-number">
              <h3 > <strong>Bill: </strong>{item.billNumber}</h3>
              </div>
               <div style={{flex: 1,textAlign: 'right'}} className="time-date">
               <h3> <strong>Time: </strong>{item.created_datetime}</h3>
               </div>
                ----------------------------------
                ----------------------------------
                ---------------------------------- 
                -------------------- 
               
                <div>
                <h3 > <Display message={counter}/>x <strong>Title: </strong>{item.title}</h3>
                <ButtonIncrement style={{flex: 1,textAlign: 'left'}} className="increase" onClickFunc={incrementCounter}/>
                <ButtonDecrement style={{flex: 1,textAlign: 'left'}} className="decrease" onClickFunc={decrementCounter}/>
                
             
                </div>
                <div style={{textAlign: 'right'}} >
                <h3> <strong>Price: </strong> {item.price}</h3>     
                </div>
                <div>
               <span>Total: </span>     
                </div>
     
                </React.Fragment>
        )}

            </div>
         
          </div>
          <div lassName="button"
          style={{textAlign:"center"}}>
            <Link to={{
            pathname:'/',
          }}>
            <button>
            Analyse Receipt
            </button>

          </Link>
      

          </div>

          

    </div>
    )
  }


const mapStateToProps = state => {
  return {
    items: state.items
  }
}

const mapDispatchToProps = dispatch => {
  return {
    getItems: () => dispatch(getItems())
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BillList)

行動:

    import { GET_ITEMS, ITEMS_ERROR  } from "../types";
    import axios from 'axios'
    
    
    export const getItems = () => async (dispatch) => {
    
        try{
            const res = await axios.get('http://localhost:8000/api/bills/')
            dispatch({
                type: GET_ITEMS,
                payload: res.data
            })
            
        }
        catch(e){
            dispatch({
                type: ITEMS_ERROR,
                payload: console.log(e),
            })
           
        }
        
    
    
    }


**App.js:**


    function App({items}) {
    
      function ItemPost() {
        let { id } = useParams();
        return <div style={{ fontSize: "50px" }}>
                 Now showing post {id}
               </div>;
      }
    
      
      return (
        <Router>
        <div className="app">
            <main>
              <Switch>
                <Route exact path="/" component={Items}>
        
                </Route>
    
                <Route exact path="/bills/" component={BillList}>
                  <BillList items={items}/>
                   </Route>
    
                   <Route exact path="/bills/:id" component={BillList}>
                  <ItemPost/>
                   </Route>
    
                
    
    
              </Switch>
    
            </main>
          
       
        </div>
        </Router>
      );
    }

行動:

export const getItems = () => async (dispatch) => {


    try{
        const res = await axios.get(`http://localhost:8000/api/bills/`)
        dispatch({
            type: GET_ITEMS,
            payload: res.data
        })
        
    }

您可以使用 state 管理工具,例如 Redux。

使用 Axios 獲取數據后,將其保存到 Redux 存儲中。 這樣做可以使數據可供其他組件使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM