【发布时间】:2020-10-07 23:39:20
【问题描述】:
我正在尝试在我的 react 应用程序中实现 redux。到目前为止,我已经创建了 4 个操作来管理我的应用程序“项目”。前三个; GET_ITEMS、DELETE_ITEM 和 ADD_ITEM 可以完美地工作,并且很容易与我现有的 react 应用程序相结合。第四个“TOGGLE_ITEM”实际上起作用并切换项目,但不知何故破坏了我现有的反应组件。我的 Items.js 文件中出现“项目”未定义错误。这是代码,带星号的行非常重要:
- 根组件 = Musiclist.js:
class MusicList extends Component {
componentDidMount() {
this.props.getItems();
*console.log(this.props.item.items)*
// Console log returns the proper items array that gets passed down below to the Items component
}
toggle = (id) => {
*this.props.toggleItem(id)*
// Pings the item reducer and executes the toggle function, which functions properly
}
delItem = (id) => {
this.props.deleteItem(id)
}
addItem = (url) => {
this.props.addItem(url)
}
render() {
*const { items } = this.props.item*
// Same as saying this.props.item.items
return (
<div>
<AddItem addItem={this.addItem}/>
*<Items items = {items} toggle = {this.toggle} delItem = {this.delItem} />*
// Takes in the array items as a prop and the function toggle() as a prop
</div>
)
}
}
MusicList.propTypes = {
getItems: PropTypes.func.isRequired,
deleteItem: PropTypes.func.isRequired,
addItem: PropTypes.func.isRequired,
toggleItem: PropTypes.func.isRequired,
item: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
item: state.item
})
export default connect(mapStateToProps, { getItems, deleteItem, addItem, toggleItem})(MusicList);
Reducer = itemReducer.js:
这似乎工作得很好,并且按预期工作。我也看不出这会影响 Items 组件的任何明显原因,因此它可能是一次红色听证会......但我只是在实施后才开始遇到问题。
case TOGGLE_ITEM:
return {
items: state.items.map(item => {
if(item.id === action.payload) {
item.isOpen = !item.isOpen
}
})
}
问题组件 = Items.js:
引发错误的组件。
import React, { Component } from 'react';
import Item from "./Item";
import PropTypes from "prop-types";
class Items extends Component {
componentDidMount() {
// Console logs the same array as the one in MusicList.js
*console.log(this.props.items)*
this.props.items.map((item) => (
// Console logs as it's supposed to, maps the items and prints them, no "item undefined" error
console.log(item)
))
}
render() {
return this.props.items.map((item) => (
<div>
// "item" is undefined on this line despite the map function defining it above.
// I did not change any code here when implementing redux, yet there was no error before redux.
*<Item key = {item.id} item = {item} toggle = {this.props.toggle} delItem = {this.props.delItem} isOpen = {item.isOpen}/>*
</div>
));
}
}
// PropTypes
Items.propTypes = {
items: PropTypes.array.isRequired
}
export default Items;
非常感谢任何帮助!
【问题讨论】:
-
正确的切换更新还应该复制任何现有状态并在映射中返回新的项目对象引用,即
return { ...state, item: state.items.map(item => item.id === action.payload ? { ...item, isOpen: !item.isOpen } : item), }。由于您在实施TOGGLE_ITEM后才遇到问题,在您尝试切换项目之前是否可以安全地假设 UI 代码正常?能否提供更完整的代码示例和复现步骤? running 代码框将非常有用,因此我们可以对其进行实时调试。
标签: javascript reactjs react-native redux react-redux