【发布时间】:2017-12-30 19:58:02
【问题描述】:
您好,我正在尝试从 Stephen Grider 的 react-native 课程中学习 react native。我坚持从我的 web 服务加载数据并使用 redux 和 lodash 列出它们。我可以成功获取数据并可以在渲染中看到它(console.log) ,但我的道具在 componentDidUpdate 或 componentWillMount 中始终为空。 任何帮助表示赞赏,谢谢。 减速机是这样的;
import { TEST_FETCH, TEST_LOAD } from "../actions/types";
const INITIAL_STATE = { dataSource: [] };
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case TEST_FETCH:
return { ...state, loading: false, dataSource: action.payload.data };
case TEST_LOAD:
return { ...state, loading: true, error: "" };
default:
return state;
}
};
动作是;
import { TEST_LOAD, TEST_FETCH } from "./types";
export const getdata = ( ) => {
return dispatch => {
dispatch({ type: TEST_LOAD });
fetch("http://myserver/getdata", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => {
return response.json();
})
.then(responseData => {
return responseData;
})
.then(data => {
// return data;
dispatch({ type: TEST_FETCH, payload: data });
});
};
};
页面是;
import _ from 'lodash';
import React, { Component } from "react";
import { View, Text, ListView } from "react-native";
import { connect } from "react-redux";
import { getdata } from "../actions";
class testList extends Component {
componentWillMount() {
this.props.getdata();
}
componentDidMount() {
console.log(this.props.myarray ); // myarray is empty
this.createDataSource(this.props.myarray);
}
componentDidUpdate() {
console.log(this.props.myarray ); // I tried this but still myarray is empty
this.createDataSource(this.props.myarray);
}
createDataSource({ dtsource }) {
// sure dtsource is null too
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2});
this.dataSource = ds.cloneWithRows(dtsource);
}
render() {
console.log(this.props.myarray); // if I write here,I can see my json's output
return <View>
<Text>Employee List</Text>
<ListView dataSource={this.props.myarray} renderRow={rowData => <Text
>
{rowData}
</Text>} />
</View>;
}
}
const mapStateToProps = state => {
const myarray= _.map(state.testForm.dataSource, function(v) {
return { ...v };
});
return { myarray};
};
export default connect(mapStateToProps , { getdata })(testList);
【问题讨论】:
-
您应该从 componentDidMount 发送您的操作。见reactjs.org/docs/react-component.html#componentwillmount。
-
this.props.arr1来自哪里? -
@CarlosC 对不起,我在这里写的时候忘记改了。这是 myarray
-
您将
mapDispatchToProps传递给connect()。应该是mapStateToProps。 -
@AdamKipnis 我更正了,但我在这里写错了。对不起