【发布时间】:2019-08-10 10:27:50
【问题描述】:
我有一个应用程序,它首先根据道具显示汽车列表,但单击 sort 按钮会将显示转换为按字母顺序排列的列表。
我正在尝试设置一个函数,每次单击sort 按钮时都会更改buttonClicked 的状态(运行sortAlphabetically。
React 文档中的条件渲染教程专注于按钮 within 中的文本,但我试图根据是否有单独的按钮在我的渲染方法中有条件地渲染 JSX点击。
这是我目前的代码,它返回Parsing error: this is a reserved word。
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: [],
buttonClicked: false
};
}
sortAlphabetically = () => {
handleSortClick();
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: {cars: orgArray} })
}
componentDidMount() {
this.props.getCars()
// this.setState({cars: this.props.cars})
}
handleSortClick() {
this.setState({
buttonClicked: !this.state.buttonClicked})
}
render() {
const buttonClicked = this.state.buttonClicked
let display;
if (this.state.buttonClicked = false) {
display = {this.state.cars.cars && this.state.cars.cars.map(car => <CarCard key={car.id} car={car}/>)}
} else {
{this.props.cars.cars && this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}
}
return (
<div className="CarsContainer">
<h3>Cars Container</h3>
<button onClick={this.sortAlphabetically}>Sort</button>
{display}
<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);
最终,我正在尝试执行以下操作:
- 将
buttonClicked的初始状态设置为false - 每当运行
sortAplhabetically时切换buttonClicked的布尔值 - 当false时显示
this.state.cars.cars && this.state.cars.cars.map(car => <CarCard key={car.id} car={car}/>)} - 当为真时显示
{this.props.cars.cars && this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}
非常感谢任何帮助。
【问题讨论】:
-
我很确定您的默认道具定义错误。它们应该在您的
Cars类之后,并且语法应该更改为Cars.defaultProps = {...
标签: javascript reactjs conditional-formatting