Redux存储更新时,React组件未呈现。
如果我使用设置超时,则可以在控制台中查看数据。为什么组件无法渲染。
这里的问题是为什么我的组件没有得到更新。我已经附上了下面的代码。
组件
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux';
import requestAPI from '../actions/getuseraction'
class Viewdetails extends Component {
componentDidMount() {
this.props.onGetuserlist('all')
}
render() {
console.log("this.props.userlist")
setTimeout(() => {
console.log(this.props.userlist)
this.props.userlist.map((item,i)=>{
console.log(i)
})
}, 1000);
const data = this.props.userlist.map((item,i)=>{
return <tr>
<td>{item.name}</td>
<td>{item.name}</td>
<td>{item.name}</td>
<td>{item.name}</td>
<td>{item.name}</td>
<td>{item.name}</td>
</tr>
})
return (
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Joindate</th>
<th>Country</th>
<th>Gender</th>
<th>Skills</th>
</tr></thead>
<tbody>
{data}
</tbody>
</table>
</div>
)
}
}
function mapStateToProps(state) {
return {
userlist: state.userlist,
};
}
function mapActionstoProps(dispatch) {
return {
onGetuserlist: bindActionCreators(requestAPI, dispatch),
};
}
export default connect(mapStateToProps, mapActionstoProps)(Viewdetails)
动作
function requestAPI(type) {
console.log("requestAPI")
switch (type) {
case 'country':
let countryist = [];
getcountryist()
.then(data => countryist.push(...data.resultSet))
.catch(reason => console.log(reason.message))
return {
type: 'countrylist',
payload: countryist
};
case 'all':
let userlist = [];
getlistofuser()
.then(data => userlist.push(...data.resultSet))
.catch(reason => console.log(reason.message))
return {
type: 'userlist',
payload: userlist
};
}
}
export default requestAPI;
async function getlistofuser() {
let response = await fetch('https://api.myjson.com/bins/13g2pv');
let data = await response.json();
return data;
}
async function getcountryist() {
let response = await fetch('https://api.myjson.com/bins/1g9fqv');
let data = await response.json();
return data;
}
减速器
function getalluserlist(state = [], action) {
console.log("Reducer")
console.log(action.payload)
switch (action.type) {
case 'userlist':
return action.payload
default:
return state
}
}
export default getalluserlist;
答案 0 :(得分:1)
您需要在化简器中返回一个新的对象实例。
React需要一个对象的新引用来找出已更改的状态。
传递action.payload
时,将在获取数据后返回相同的实例。
function getalluserlist(state = [], action) {
switch (action.type) {
case "userlist":
return action.payload;
default:
return state;
}
}
因此返回一个新的引用(我猜该状态的形状为[]
)。
function getalluserlist(state = [], action) {
switch (action.type) {
case "userlist":
return [...state, action.payload];
default:
return state;
}
}