相关疑难解决方法(0)

forceUpdate()与带有回调的this.setState()

这样做的原因是处理具有state自己功能的变量.我有两种方式可以想到.一种是this.state通过调用状态函数直接变异(好吧,有点,我知道它是不鼓励的),然后调用forceUpdate()并处理它带来的东西.另一种是做回调函数.哪种方法适当?

这是我所谈论的一个例子.我正在使用Vis.js,他们的DataSet对象允许您将数据添加到现有数据集 - 例如节点和边缘.

  addDataToGraph: function(data) {
    // Is this the proper way to do something like this?
    this.state.graphData.nodes.add(nodes);
    this.state.graphData.edges.add(edges);
    this.forceUpdate();

    // Or is this the right way - the question I am posing here
    this.setState({
      currentChunk: data.currentChunk,
      totalChunks: data.totalChunks
    }, function() {
      this.state.graphData.nodes.add(data.nodes);
      this.state.graphData.edges.add(data.edges);
    }.bind(this));
  }
Run Code Online (Sandbox Code Playgroud)

reactjs

7
推荐指数
1
解决办法
2万
查看次数

如何在 React 中设置类对象的状态?

我的类中有一个正在修改的对象数组,只有当发生按键时我才想以可视方式呈现该对象。

class Example extends React.Component {
    constructor(props) { 
       super(props); 
       this.myArr = []; // this is an array of objects 
    }

    render() {  
       return (
        ???
       );
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我用多种不同的方法修改 this.myArr 的内容。只有当我准备好时(在按键或其他事件上)我才想渲染它。

现在,在我的 render() 中,我应该引用this.myArr,然后this.forceUpdate()在我想强制重新渲染时使用。

或者我应该将 myArr 移入this.state.myArr,并在我的方法中修改 this.state.myArr ,当我准备好显示它时,在我的 render() 引用this.state.myArr中,并以某种方式强制重新渲染this.setState(myArr: this.state.myArr);

javascript reactjs

5
推荐指数
1
解决办法
1万
查看次数

缺点直接改变状态和forceUpdate()vs setState

反应文档说Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable...但是当我根本不使用setState()时这是一个非问题.

我能想到的唯一缺点是:

  • 无法使用shouldComponentUpdate/ componentWillUpdate/ componentDidUpdate比较新旧状态.

  • 对于其他人来说,可能会使维护更加困难.因为它不是做事的标准方式.

但是没有使用setState()和直接改变状态还有其他缺点吗?


编辑:我删除了我的理由为什么我被这个想法所吸引.我知道这是一种反模式,我知道这可能不是最好的方式.但这个问题都是关于"为什么"的问题.

EDIT2:这里的关键词other也在... are there any other disadvantages ...

javascript reactjs

4
推荐指数
1
解决办法
672
查看次数

标签 统计

reactjs ×3

javascript ×2