我做成员组件。
在componentDidMount()
中调用函数getMemberList()
class Members extends Component{
constructor(props) {
super(props);
this.state = {
members: []
}
}
componentDidMount() {
getMemberList(this.props);
}
render() {
return (
<div>
<div>Members</div>
{this.state.members.map((member) => (
<li key={member.id}>
{member.name}
</li>
))}
</div>
);
}
}
export default connect((state) => state)(Members);
调用函数getMemberList()
时,它将连接服务器并放入成员数据,并进行操作和调度。
export function getMemberList(props){
axios.get('/api/members')
.then(function (response) {
// handle success
let data = response.data;
let members = data.data;
let action = {
type: 'GET_MEMBERS',
members: members,
};
props.dispatch(action);
})
.catch(function (error) {
// handle error
console.log(error);
return {
type: 'GET_MEMBERS_ERROR',
authenticated: false
};
})
.finally(function () {
// always executed
});
}
然后调用reducer并将成员设置为状态。 看来效果很好。
const initData = {
members: []
}
export function memberReducer(state = initData, action){
switch (action.type) {
case 'GET_MEMBERS':
return {
members: action.members
};
case 'GET_MEMBERS_ERROR':
return state;
default:
return state;
}
}
但是我的理解是渲染应该在派遣后调用。 JSX中的成员列表未更新。
是我误会了吗?
请帮助并给我一个建议。
答案 0 :(得分:1)
您的组件应如下所示:
class Members extends Component {
componentDidMount() {
getMemberList(this.props);
}
render() {
return (
<div>
<div>Members</div>
{this.props.members.map(member => (
<li key={member.id}>{member.name}</li>
))}
</div>
);
}
}
// this function takes your redux state and returns an object with a key of members to your component. You will be able to access the members value in your component by this.props.members - again, it's mapped your redux STATE to your react PROPS
const mapStateToProps = state => {
return {
members: state.members
};
};
export default connect(mapStateToProps)(Members);
members
数组应来自您的redux存储。在组件中,您正在查看处于反应状态的members
数组。那里什么也没有,也没有被更新。
您需要将Redux状态映射到您的组件。在上面的代码段中,mapStateToProps
/ connect
就是这样做的。您正在使用redux状态,并将值通过connect
组件传递给您的react道具。
我不确定您通过getMemberList
到this.props
的经历。