我创建了函数get_marketing_updates_from_projects
,从中返回修改后的对象数组列表。
代码:
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import { fetchMarkets } from '../actions/MarketingCardAction';
import _ from 'lodash';
function get_marketing_updates_from_projects(projects)
{
let all_marketing_plans = [];
_.each(projects, function(project) {
// all_marketing_plans = project.marketingplans.reduce(marketing_plan_array_reducer, all_marketing_plans);
project.marketingplans.reduce( function(coll, marketing_plan){
coll.push( _.extend(marketing_plan, {"project_name": project.name, "project_id": project.id}));
return coll;
}, all_marketing_plans );
});
console.log("All marketing plans", all_marketing_plans);
return all_marketing_plans;
}
class MarketingCard extends Component {
constructor(props) {
super(props);
let marketing_plan_projects = [];
this.props.markets.data ? marketing_plan_projects = this.props.markets.data : null;
this.state = {
marketing_updates : get_marketing_updates_from_projects(marketing_plan_projects),
query: '',
}
}
componentDidMount (){
this.props.fetchMarkets();
}
filterMarketingUpdates = (marketing_updates) => {
const formatQuery = this.state.query.toLowerCase();
return _.filter(marketing_updates, marketing_update => {
return this.contains(marketing_update.project_name, formatQuery);
});
};
contains = (name, query) => {
if (name.toLowerCase().includes(query)) {
return true;
}
return false;
};
onQueryChange = query => {
this.setState({ query });
};
render() {
const filtered_marketing_updates = this.filterMarketingUpdates(this.state.marketing_updates);
//console.log(filtered_marketing_updates)
return (
<ScrollView style={styles.container}>
<Text>Hello World</Text>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingLeft: 15,
paddingRight: 15
},
});
const mapStateToProps = state => ({
markets: state.markets.items
})
export default connect (mapStateToProps, { fetchMarkets })(MarketingCard);
注意:如果我在render()中执行console.log(this.props.markets.data);
,那么我可以在控制台中看到整个数据,但是现在我想对其执行reduce()操作,但是我得到的是空数组[]为什么?
我只想将this.props.markets.data
分配给marketing_plan_projects
,然后在marketing_plan_projects
上执行reduce(),这样我就可以获得marketing_updates
即新的修改数据。
屏幕截图:
答案 0 :(得分:1)
我知道了。由于您在DidMount
上填写了道具,因此当道具更改时,您可能需要更改状态。因此,您可能需要声明WillReceiceProps
事件。
componentWillReceiveProps(nextProps) {
// You don't have to do this check first, but it can help prevent an unneeded render
let marketing_plan_projects = [];
nextProps.markets.data ? marketing_plan_projects = nextProps.markets.data : null;
const marketing_updates = get_marketing_updates_from_projects(marketing_plan_projects);
if (!_.isEqual(marketing_updates, this.state.marketing_updates)) {
this.setState({
marketing_updates,
});
}
}