【发布时间】:2018-02-16 16:40:35
【问题描述】:
我从最近几天开始学习 React Redux。我已经建立了一个小应用程序。我正在尝试将数据发送回 API,其中包含新闻对象的更新点赞。
这是新闻项目组件的代码。
import React, { Component} from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux';
import { updateArticleLikes } from '../../actions/updateNews';
class NewsItem extends Component {
constructor(){
super()
this.state = {
likes: 0,
key: ''
}
}
componentDidMount(){
this.setState({
likes: this.props.item.likes,
key: this.props.item.key
})
}
increaseCount = event => {
this.newState(event);
}
newState = (event) => {
console.log(this.state)
this.setState({
likes: this.props.item.likes + 1,
key: this.props.item.key
}, this.submitUpdate(event))
}
submitUpdate = (event) => {
event.preventDefault();
// console.log(this.state)
this.props.updateArticleLikes(this.state)
this.setState({likes: 0, key: ''})
}
render(){
const {item } = this.props
return(
<div key={item.key} >
<h4> - <a href={item.url} target="_blank" rel="noopener noreferrer">{item.title} </a></h4>
<button onClick ={ this.increaseCount } data-likes={item.likes} value={item.key}>Like { this.state.likes }</button>
</div>
)
}
}
const mapDispatchToProps = dispatch => {
return bindActionCreators(
{ updateArticleLikes }, dispatch);
};
export default connect(null, mapDispatchToProps)(NewsItem);
这里是 updateArticleLikes 操作的代码。
import { API_URL } from '../global';
export function updateArticleLikes(data) {
// here, it shows old state in data
console.log(data)
return dispatch => {
console.log(JSON.stringify({"article": data}))
return fetch(API_URL + '/newsupdate', {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"article": data})
})
}
}
问题是由于某种原因,函数 updateArticleLikes 正在接收先前的状态。我确信 newState 函数正在更新本地状态,因为我可以在按钮标签 ({this.state.like}) 中的 DOM 中看到它的值,但我不明白为什么 action 正在接收先前的状态。
我想到了 mapStateToProps,但在这种情况下它不起作用,因为我正在处理本地状态。从前两天开始不能让它工作!有什么建议吗?
行之有效的解决方案:
Oblosys 帮我解决了这个问题。从 submitUpdate 函数中删除参数并删除 seState 和 preventDefault 我的函数现在运行良好。它正在更新和显示正确的状态,并向服务器发送正确的数据。这是我为遇到相同问题的任何人更改的代码。
newState = (event) => {
console.log(this.state)
event.persist()
this.setState({
likes: this.props.item.likes + 1,
key: this.props.item.key
}, this.submitUpdate)
}
submitUpdate = () => {
this.props.updateArticleLikes(this.state)
}
【问题讨论】:
标签: reactjs redux react-redux