简体   繁体   English

我如何使用带有 redux 和 react.js 的按钮将数据从一个组件传递到另一个组件?

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

i am working on a Billing list project..... and whenever the user clicks on a button in the Item Page, the button should send one random item with the Fetched API to the second page which is the Billing page and it should match and display the information!我正在做一个计费列表项目......每当用户点击项目页面中的一个按钮时,该按钮应该发送一个带有 Fetched API 的随机项目到第二页,即计费页面,它应该匹配并显示信息!

After fetching the data with Axios i managed to save it to the Redux store.... I tried to use props to send the data or display it but nothing works, it returns an error saying TypeError: Cannot read property 'props' of undefined ....?在使用 Axios 获取数据后,我设法将其保存到 Redux 商店....我尝试使用 props 发送数据或显示它但没有任何效果,它返回一个错误提示 TypeError: Cannot read property 'props' of undefined ....? What am i doing wrong ?我究竟做错了什么 ?

I Would really appreciate some feedback or any suggestions that would help me.我真的很感激一些反馈或任何对我有帮助的建议。 Thanks!谢谢!

Here is my code for the Item page :这是我的项目页面代码

    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)

Here is my Billing page Code :这是我的计费页面代码

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)

Action:行动:

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

Action:行动:

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


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

You could use a state management tool like Redux for example.您可以使用 state 管理工具,例如 Redux。

After fetching the data with Axios save it to the Redux store.使用 Axios 获取数据后,将其保存到 Redux 存储中。 Doing that makes the data available to be used by another components.这样做可以使数据可供其他组件使用。

暂无
暂无

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

相关问题 如何在 React.JS 中将数据从一个组件传递到另一个组件 - How to pass data from one component to another in React.JS 当我按下按钮时如何将数据从一个组件发送到另一个组件。 React.js - how to send the data from one component to another component when i press a button. React.js 如何在 React.js 中将状态/数据从一个组件传递到另一个组件(特别是 riot api) - How to pass state/data from one component to another in React.js (riot api specifically) 如何在 React.js 中将数据从一个 function 传递到另一个 - How to pass data from one function to another in React.js React - 如何将 API 数据从一个组件传递到另一个 js 文件中的另一个组件? - React - How can I pass API data from one component to another in a different js file? 在 React.js 中如何将表单的值从一个组件传递到另一个组件 - In React.js How to pass values of form from one component to another component 如何在 React.js 中使用 onClick() 事件将道具从一个组件传递到另一个组件 - How to pass props from one Component to another component with onClick() event in React.js React / Redux:如何将此状态从一个组件传递到另一个文件? - React/Redux: How can I pass this state from one component to another file? 如何在 React.js 中将 useState 值从一个组件传递到另一个组件 - How to pass useState Value from One Component to another one in React.js React js:我可以将数据从一个组件传递到另一个组件吗? - React js: can I pass data from a component to another component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM