如何使用Redux更新全局状态并从全局状态中删除项目

时间:2020-03-09 14:39:01

标签: javascript reactjs redux react-redux

我正在尝试学习redux,但是我对如何正确使用动作中使用的deleteCar感到困惑。减速器工作正常,但问题出在cars的全局状态下,如何在Car组件中更新汽车的状态,然后调用deleteCar函数并修改{{1}的状态}。当我在cars组件中打印汽车状态时,它为空。

我有一个名为Cars的组件,它是Car(单个汽车)的父组件。

Car

单车

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

class Cars extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cars: []
    };
  }
  componentDidMount() {
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({ cars: data }));
  }
  render() {
    const { cars } = this.state;
    return (
      <div>
        {cars.map(c => (
          <Car key={c.id} make={c.make} price={c.price} id={c.id} />
        ))}
      </div>
    );
  }
}

const mapStateToProps = reduxStoreState => {
  return {
    cars: reduxStoreState.cars
  };
};

export default connect(mapStateToProps)(Cars);

动作

import React from "react";
import { deleteCar } from "../../actions/delete";
import { connect } from "react-redux";

const Car = ({ deleteCar, make, price, id }) => {
  return (
    <div className="card m-4">
      <div className="row">
        <div className="col">
          <h3>{make}</h3>
          <p>{price}</p>
        </div>
      </div>
      <div className="row">
        <button
          className="btn btn-danger"
          onClick={() =>
            deleteCar({
              id: id,
              make: make,
              price: price
            })
          }
        >
          Delete Car
        </button>
      </div>
    </div>
  );
};
const mapStateToProps = reduxStoreState => {
  return {
    cars: reduxStoreState.cars
  };
};

export default connect(mapStateToProps, { deleteCar })(Car);

减速器

import { DELETE } from "../constants";
export const deleteCar = (payload) => {
  return {
    type: DELETE,
    payload: payload
  };
};

1 个答案:

答案 0 :(得分:2)

下面的代码将无法正常工作:

adapter.submitList(list)

在JavaScript中,对象存储在变量中作为引用。通过这样调用delete操作:

cars: state.cars.filter(obj => obj !== action.payload)

您每次都创建一个新对象,因此它们将永远不匹配,也不会被过滤。

它出现 ,就像进行比较:

deleteCar({
  id: id,
  make: make,
  price: price
})

但实际上,它的比较如下:

{ id: id, make: make, price: price } === { id: id, make: make, price: price }

相反,我建议像这样通过// Both objects contain the same values // But will not evaluate as equal because the references are different 'object_reference_1' === 'object_reference_2' 进行检查:

id

第二个问题是您在cars: state.cars.filter(obj => obj.id !== action.payload.id) 中复制了本地和redux状态。

派遣一个操作来填充redux,而不是使用本地状态。看起来可能像这样:

Cars

然后在减速器中添加这种情况:

componentDidMount() {
  fetch(url)
  .then(response => response.json())
  // Or preferably create a new action and call it like you did `deleteCar`
  .then(data => this.props.dispatch({ type: 'INITIALIZE', cars: data }));
}

确保删除switch (action.type) { case 'INITIALIZE': return { ...state, cars: action.payload }; 的本地状态,并替换cars以使用const { cars } = this.state;

相关问题