简体   繁体   English

Redux - 如何从商店获取数据并将其发布

[英]Redux - How to get data from store and post it

Newbie to Redux here, I have tried to follow a couple tutorials and I am not clear of how Redux actually works. Redux 的新手,我尝试按照几个教程进行操作,但我不清楚 Redux 的实际工作原理。 It was mentioned that the store of Redux is to store the state of the whole tree.前面提到Redux这个store是用来存放整棵树的state的。 I have created and used actions, reducers, and store for my program and it works.我已经为我的程序创建并使用了动作、缩减器和存储,并且它有效。

The question is, how do I retrieve what is in the store?问题是,我如何取回商店里的东西? Lets say after updating my component, how can I retrieve the value inside the component and to post it?可以说在更新我的组件之后,我如何检索组件内的值并发布它?

How can I know what changed in my dropdown list and to retrieve it?我如何知道我的下拉列表中发生了什么变化并检索它?

Full code in Sandbox here https://codesandbox.io/s/elated-goldberg-1pogb沙盒中的完整代码在这里https://codesandbox.io/s/elated-goldberg-1pogb

store.js商店.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './RootReducer';

export default function configureStore() {
 return createStore(
  rootReducer,
   applyMiddleware(thunk)
 );
}

ProductsList.js ProductsList.js

import React from "react";
import { connect } from "react-redux";
import { fetchProducts } from "./SimpleActions";

class ProductList extends React.Component {
    constructor(props)
    {
        super(props);
        this.state = {
            selecteditems: '',
            unitPrice: 0
        }
    }

    componentDidMount() {
        this.props.dispatch(fetchProducts());
    }

    componentDidUpdate(prevProps, prevState) {
        if(prevState.selecteditems !== this.state.selecteditems)
        {
            this.setState((state, props) => ({
                unitPrice: ((state.selecteditems * 1).toFixed(2))
            }));
        }
    }

  render() {
    const { error, loading, products } = this.props;

    if (error) {
      return <div>Error! {error.message}</div>;
    }

    if (loading) {
      return <div>Loading...</div>;
    }

    return (
    <div>
        <select
            name="sel"
            className="sel"
            value={this.state.selecteditems}
            onChange={(e) => 
                this.setState({selecteditems: e.target.value})}
        >
            {products.map(item => 
            <option key={item.productID} value={item.unitPrice}>
                {item.itemName}
            </option>
            )}
        </select>

        <p>Unit Price: RM {this.state.unitPrice} </p>
    </div>
    );
  }
}

const mapStateToProps = state => {
  const products = state.productsReducer.items;
  const loading = state.productsReducer.loading;
  const error = state.productsReducer.error;
  return {
      products,
      loading,
      error,
  }
};

export default connect(mapStateToProps)(ProductList);

SimpleAction.js SimpleAction.js

export function fetchProducts() {
    return dispatch => {
        dispatch(fetchProductsBegin());
        return fetch('http://localhost:55959/api/products')
        .then(handleErrors)
        .then(res => res.json())
        .then(results => {
            dispatch(fetchProductsSuccess(results));
            return results;
        })
        .catch(error => dispatch(fetchProductsFailure(error)));
    };
}

function handleErrors(response) {
    if(!response.ok) {
        throw Error (response.statusText);
    }
    return response;
}

export const FETCHPRODUCTS_BEGIN = 'FETCHPRODUCTS_BEGIN';
export const FETCHPRODUCTS_SUCCESS = 'FETCHPRODUCTS_SUCCESS';
export const FETCHPRODUCTS_FAILURE = 'FETCHPRODCUTS_FAILURE';

export const fetchProductsBegin = () => ({
    type: FETCHPRODUCTS_BEGIN
});

export const fetchProductsSuccess = products => ({
    type: FETCHPRODUCTS_SUCCESS,
    payload: {products}
});

export const fetchProductsFailure = error => ({
    type: FETCHPRODUCTS_FAILURE,
    payload: {error}
});

Thanks in advance!提前致谢!

You will need to pass your action handlers to connect function您将需要传递您的操作处理程序以连接 function

connect(mapStateToProps,{actions})(ProductList).

how do I retrieve what is in the store?我如何取回商店里的东西? Lets say after updating my component, how can I retrieve the value inside the component and to post it?可以说在更新我的组件之后,我如何检索组件内的值并发布它?

if you want to see how is store change, you can add redux-logger to middleware to see that.如果您想查看商店如何变化,可以将 redux-logger 添加到中间件以查看。 when store change, it's likely a props change, you can handle this in function componentDidUpdate. store change,可能是props change,可以在function componentDidUpdate中处理。

How can I know what changed in my dropdown list and to retrieve it?我如何知道我的下拉列表中发生了什么变化并检索它?

values in dropdown is controlled by "const products = state.productsReducer.items;", productsReducer is controlled by actions you passed in dispatch like this: "this.props.dispatch(fetchProducts());".下拉列表中的值由“const products = state.productsReducer.items;”控制,productsReducer 由您在调度中传递的操作控制,如下所示:“this.props.dispatch(fetchProducts());”。

I think you should add redux-logger to know more how to redux work, it show on console step by step.我认为您应该添加 redux-logger 以了解更多 redux 是如何工作的,它会逐步显示在控制台上。 It will help you learn faster than you think:D它会帮助你学得比你想象的更快:D

to retrieve it you forgot the selecteditems找回它你忘记了selecteditems的项目

const mapStateToProps = state => {
  const products = state.productsReducer.items;
  const loading = state.productsReducer.loading;
  const error = state.productsReducer.error;
  const selecteditems = state.prodcuts.selecteditems;
  return {
    products,
    loading,
    error,
    selecteditems
  };
};

To change it you should connect another function like要更改它,您应该连接另一个 function,例如

const mapDispatchToProps = dispatch => {
    return {
        onChangeDropdownSelection: (selected)=> dispatch(actions.setSelectedDropdown(selected))
    }
}

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

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