我有 100 多个 <td>
渲染。我正在使用 NodeJS 后端获取它,将数据传递到前端,并使用 Redux 来响应组件。
我有许多呈现较少数据的组件,一切都很好,但是当涉及到这个组件时,在我刷新页面之前没有任何反应。
我尝试使用不同的生命周期(cpmponentWillMount、willRecieveProps 等),但似乎没有任何效果。
我也在使用 React-thunk 和 react-router
第一次刷新后,就不再需要了。所以基本上它只会在我第一次启动开发服务器时发生。
我坚信我必须使用组件生命周期函数之一,但我尝试了错误的函数或顺序错误?
ReportsData ==> 渲染发生的地方
class ReportsData extends Component {
constructor(props) {
super(props);
this.state = {
allReports: []
}}
getReportsData = () => {
return reportsApi.getReports().then(report => {
this.setState(() => ({
allReports: Object.assign([], report.data)
})
)});
}
componentWillMount() {
this.getReportsData(this.props);
}
render() {
// const { reports } = this.props;
const { allReports } = this.state;
let sortedReports = _.sortBy(reports, function(o) { return new moment(o.date) }).reverse();
const listReports = sortedReports.map(item => {
return (
<tr key={item.rowNumber}>
<td> {item.year}</td>
<td> {item.month}</td>
<td> {item.bruto_ukupno}</td>
<td> {item.neto_plata}</td>
<td> {item.topli_obrok}</td>
<td> {item.doprinosi}</td>
<td> {parseInt(item.ukupno_plata, 10)}</td>
<td className="table-actions">
<Link to={{ pathname: '/reports/details', state: { item } }}>
<PieChart size="21"/>
</Link>
</td>
</tr>
)});
return (
<div className="portlet-body">
<table className="table table-striped">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Gross</th>
<th>Net</th>
<th>Meals</th>
<th>Taxes</th>
<th>Salarys</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{listReports}
</tbody>
</table>
</div>
);
}
ReportsAPI
import axios from 'axios';
import {baseApiUrl} from '../config/config';
const reportsApiUrl = baseApiUrl + 'reports/'
class ReportsApi {
static getReports() {
return axios({
method: 'get',
url: reportsApiUrl + 'getReports'
})
}
}
export default ReportsApi;
reportsActions
import * as actionTypes from '../actionTypes/actionTypes';
import ReportsApi from "../api/reportsApi";
export const getReports = (data) => {
return {
type: actionTypes.GET_REPORTS,
data
}
}
export const getReportsAsync = () => {
return dispatch => {
return ReportsApi.getReports()
.then(reports => {
dispatch(getReports(reports.data));
}).catch(error => {
console.log('error while loading reports', error);
throw(error);
});
};
}
这只会在我第一次启动 DEV 服务器时发生 因此,当我提升应用程序时,我的应用程序的所有其他组件都会收到它的 Prop ,除了这个,我在任何地方都使用相同的逻辑。唯一的区别在于呈现的数据量。如果我注销并重新登录,一切都很好。如果我刷新、返回和前进,一切都很好,但是一旦我停止服务器,再次启动它,只有这个组件有这个问题。
最佳答案
你在哪里导入和使用这个组件。如果可能是在您首次呈现此组件时,您传递的 ReportData 数据可能不存在。在 componentDidMount() 生命周期方法中抛出一个 console.log(this.props) 以准确查看组件第一次渲染时的 this.props 是什么
关于javascript - Prop 仅在我刷新页面后呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869281/