我目前正在尝试将一个数组分派(dispatch)到我的 reducer ,并将其设置为我的状态以在组件上使用它。它适用于对象,但我不知道如何使用数组来做到这一点。
我的 Action 创建者:
export const loadUserItems = () => {
return async function(dispatch) {
const url_current = 'https://whateverapi';
const response = await axios.get(url_current);
const items = response.data.items;
dispatch(loadItems(items));
}
}
function loadItems(data) {
return {
type: LOAD_USER_ITEMS,
payload: data
};
}
因此,如果我在数组中获得单个项目,它就可以正常工作。 我可以将它设置为我的 reducer 中的一个对象,并在我的组件上使用它。
我的 reducer :
import {
LOAD_USER_ITEMS
} from '../actions/types';
const INITIAL_STATE = {
items: []
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case LOAD_USER_ITEMS :
return {
items: action.payload
};
default:
return state;
}
};
所以在这里,action.payload 是一个数组,我可以 console.log 它并输出该数组。该数组包含一些 JSON 对象。
但是当我尝试在组件中访问它时,它告诉我它未定义
import ... (no problems here)
class HomePage extends Component {
loadUserItems() {
this.props.loadUserItems();
}
constructor(props) {
super(props);
this.loadUserItems();
}
render() {
return (
<Container>
<Content>
<View style={styles.headerViewStyle}>
<Image
style={styles.headerImageStyle}
source={require("../assets/images/header.png")}
/>
</View>
<View>
<ItemSquareDisplay description={this.props.items[0].type}/>
</View>
</Content>
</Container>
);
}
}
const mapStateToProps = state => {
return {
items: state.items.items,
};
};
export default connect(mapStateToProps, {loadUserItems}) ( HomePage );
我的数组包含项目,第一个项目类型是“冰箱”... 但它告诉我 this.props.items[0].type 未定义。 我做了同样的事情,但只是发送了第一个项目,并且工作正常,我可以访问 this.props.items.type。但如果我发送整个数组似乎不起作用。
伙计们,还需要你们一次! 谢谢
最佳答案
原因是您正在访问一个空数组。
最初,您的项目数组是 reducer 内的一个空数组。现在,在您的组件中,您可以调用操作 loadUserItems,这将需要相当长的时间来获取数据并更新 redux 存储。在这段时间内,您的组件的渲染方法执行并尝试访问空数组的第一个元素,这肯定会出错。
因此,您可以轻松地做的是在访问数组的元素之前检查数组是否不为空。
<ItemSquareDisplay description={this.props.items && this.props.items.length > 0 ? this.props.items[0].type : ''} />
请注意,当您使用对象时起作用的原因是幸运的是,该操作在渲染方法执行和访问数组之前已经更新了 redux 存储。
关于javascript - REACT NATIVE REDUX 如何在 Action 创建者收到的reducer中设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49432022/