【发布时间】:2019-08-09 23:49:13
【问题描述】:
我有一个简单的 React/Redux 应用程序,它根据我的 Rails API 显示汽车列表。
我正在尝试添加一个按汽车名称字母顺序排列的排序功能。
虽然我的变量 orgArray 实际上在我 console.log 时按字母顺序排列,但我的 Redux 开发工具在单击排序按钮后会显示 states are equal - 因此我的 UI 没有更新。
这是我的代码:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import CarCard from '../components/CarCard';
import CarForm from './CarForm';
import './Cars.css';
import { getCars } from '../actions/cars';
import { sortCar } from '../actions/cars';
Component.defaultProps = {
cars: { cars: [] }
}
class Cars extends Component {
constructor(props) {
super(props)
this.state = {
cars: [],
sortedCars: []
};
}
sortAlphabetically = () => {
console.log("sort button clicked")
const newArray = [].concat(this.props.cars.cars)
const orgArray = newArray.sort(function (a,b) {
var nameA = a.name.toUpperCase();
var nameB = b.name.toUpperCase();
if (nameA < nameB) {
return -1;
} else if (nameA > nameB) {
return 1;
}
return 0;
}, () => this.setState({ cars: orgArray }))
console.log(orgArray)
this.props.sortCar(orgArray);
}
componentDidMount() {
this.props.getCars()
this.setState({cars: this.props.cars})
}
render() {
return (
<div className="CarsContainer">
<h3>Cars Container</h3>
<button onClick={this.sortAlphabetically}>Sort</button>
{this.props.cars.cars && this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}
{/* {this.state.cars.cars && this.state.cars.cars.map(car => <CarCard key={car.id} car={car} />)} */}
<CarForm />
</div>
);
}
}
const mapStateToProps = (state) => {
return ({
cars: state.cars
})
}
const mapDispatchToProps = (dispatch) => {
return {
sortCar: (cars) => dispatch(sortCar(cars)),
getCars: (cars) => dispatch(getCars(cars))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Cars);
我会猜到mapStateToProps 或在我最初的setState 中添加sortedCars: [] 会起作用。
基本上,我的道具正在更新,但我的状态也需要更新 - 尽管我不确定我缺少什么。
更新:
如果有帮助,这是我的动作创建者和异步动作:
const sortCars = cars => {
return {
type: 'SORT_CARS',
cars
}
}
// Async Actions
export const sortCar = (cars) => {
console.log(cars, 'cars object');
return dispatch => {
dispatch(sortCars(cars))
}
}
更新:
这也是 Reducer:
export default (state = {cars: []}, action) => {
switch(action.type) {
case 'GET_CARS_SUCCESS':
return Object.assign({}, state, {cars: action.payload})
case 'CREATE_CAR_SUCCESS':
return Object.assign({}, state, {cars: action.payload})
case 'REMOVE_CAR;':
return state.filter(car => car.id !== action.id)
case 'SORT_CARS;':
return Object.assign({}, state, { cars: action.payload})
default:
return state;
}
}
【问题讨论】:
-
您可以在解析器中对数组进行排序吗?似乎没有必要将数组传递两次,一次未排序,一次排序。
-
抱歉,我不知道你说的
resolver是什么意思 -
对不起,减速机
-
等等,你的代码让我很困惑。在 sort 函数中,
return 0;之后的右括号是什么? -
@James 是的,我会确保进入您的视图的数据已排序、清理并准备好使用。