Javascript 延迟组件的安装,直到事件发生
我正在实现一个React应用程序,用户可以在其中喜欢或不喜欢帖子。相同的信息会立即发布到服务器。我也在我的应用程序中使用了Javascript 延迟组件的安装,直到事件发生,javascript,reactjs,redux,Javascript,Reactjs,Redux,我正在实现一个React应用程序,用户可以在其中喜欢或不喜欢帖子。相同的信息会立即发布到服务器。我也在我的应用程序中使用了redux和react-router。下面是SocialCount.js组件,用于处理帖子中的好恶 import { post } from 'jquery'; import React from 'react'; import { connect } from 'react-redux'; class SocialCount extends React.Component
redux
和react-router
。下面是SocialCount.js
组件,用于处理帖子中的好恶
import { post } from 'jquery';
import React from 'react';
import { connect } from 'react-redux';
class SocialCount extends React.Component{
constructor(props){
super(props);
console.log(props);
this.state={
likes: props.likes,
likeUpdated: false,
dislikes: props.dislikes,
dislikesUpdated: false,
postId: props.postId,
baseUrl: 'http://snaptok.herokuapp.com/'
}
handleLike=()=>{
//A lot of calculation on state happenes here and post to server
}
handledislikes=()=>{
//A lot of calculation on state happenes here and post to server
}
render(){
console.log(this.props)
return(<>
<li>
<button>
{this.state.likeUpdated?<i class="fa fa-thumbs-up" aria-hidden="true" style={{fontSize: 'large'}} onClick={this.handleLike}></i>:<i class="fa fa-thumbs-o-up" aria-hidden="true" style={{fontSize: 'large'}} onClick={this.handleLike}></i>}
<span>{this.state.likes}</span>
</button>
<button>
{this.state.dislikesUpdated?<i class="fa fa-thumbs-down" aria-hidden="true" style={{fontSize: 'large'}} onClick={this.handledislikes}></i>:<i class="fa fa-thumbs-o-down" aria-hidden="true" style={{fontSize: 'large'}} onClick={this.handledislikes}></i>}
<span>{this.state.dislikes}</span>
</button>
</li>
<li>
<a>{this.props.length} Comments</a>
</li>
</>)
}
}
export default SocialCount;
从“jquery”导入{post};
从“React”导入React;
从'react redux'导入{connect};
类SocialCount扩展了React.Component{
建造师(道具){
超级(道具);
控制台日志(道具);
这个州={
喜欢:道具,喜欢,
likeUpdated:错误,
不喜欢:道具,不喜欢,
不喜欢更新:错误,
posted:props.posted,
baseUrl:'http://snaptok.herokuapp.com/'
}
手感=()=>{
//这里发生了大量关于状态的计算,并将其发送到服务器
}
handledislikes=()=>{
//这里发生了大量关于状态的计算,并将其发送到服务器
}
render(){
console.log(this.props)
返回(
{this.state.likeUpdated?:}
{this.state.likes}
{this.state.dislikesUpdate?:}
{this.state.dishaves}
{this.props.length}注释
)
}
}
导出默认社会帐户;
道具来自连接到redux商店的父级。我没有将SocialCount连接到商店的原因是道具无法更改,但状态可以更改
现在让我们来讨论这个问题。在应用程序中转到其他路线,然后返回到SocialCount组件时,会保留在转到其他路线之前传递给它的旧道具。它不接受来自家长的新道具。因此,我在帖子上看到旧的喜欢和不喜欢的道具,即使有新的道具可用
这意味着在将操作分派到存储区之前,SocialCount的构造函数会执行并使用旧的道具初始化状态。
因此,当新道具出现时,状态不会改变,因此我会看到喜欢和不喜欢的旧信息。我需要的是像componentDidReceiveProps
这样的方法来解决上述问题。但它不存在。因此,我需要构造函数在新道具可用之前不执行,或者在检测到新道具时更改状态
请帮我解决这个问题,给我提些解决办法
谢谢!不要更新状态以匹配道具。只需在渲染方法中直接访问道具即可 i、 e.
{this.props.likes}
您可能希望此组件完全无状态您所说的非常正确,但我需要“喜欢”和“不喜欢”按钮上的所有操作都在此状态下进行。我们无法更改子组件中的道具。这就是为什么我使用状态来处理这些操作。当用户喜欢或不喜欢帖子时,信息此组件本身中的应用程序已发布到服务器。我明白了。此模式有点尴尬,因为您在两个位置跟踪应用程序状态,没有单一的真实来源。一个是此组件内部的状态,但也在redux中。我建议更改您的模式,以便在状态更改时更新redux本身。此组件可以如果需要,我会发出更新请求,但它会从redux读取数据