【问题标题】:Which Reactjs lifecycle event should this method go in?这个方法应该进入哪个 Reactjs 生命周期事件?
【发布时间】:2018-03-20 19:06:48
【问题描述】:

我正在编写一个简单的 reactjs 组件,它根据套接字和 api 调用进行更新。目前,当单击侧边栏项 (NavBarSide) 时,会执行 handleNavClick 方法。这将根据在服务器端处理的查询返回一个代码。这会将状态设置为新的股票代码。这会更新标题栏,但不会更新图表。从我目前对 react 的理解来看,这是因为更新时没有调用 componentWillMount() 方法,因此没有形成新的套接字连接。

我应该将componentWillMount() 函数中的代码复制到另一个生命周期事件吗?或者编写另一个处理股票更新的函数?

import IO from 'socket.io-client';
import React from "react";

import { BrowserRouter as Router } from "react-router-dom";
import { Dashboard } from "./components/Dashboard";
import { NavBar } from "./components/NavBar";
import { NavBarSide}  from "./components/NavBarSide";

import { render } from "react-dom";

import "bootstrap/dist/css/bootstrap.css";
import "../css/index.css";
import 'whatwg-fetch';

let ftse100Tickers = require('./ftse_100_tickers.json');
let randomInt = Math.floor(Math.random() * ftse100Tickers.tickers.length);

class App extends React.Component {
    static getTimeSeries(dataSet){
        return dataSet.map(row => row.time_stamp)
    }

    constructor(){
        super();
        this.state = {
            volumeChart: {
                labels: [],
                datasets: [
                    {
                        label: 'Volume',
                        data: [],
                        fill: false,
                        borderColor: "rgb(255, 238, 187)"
                    },
                ]
            },
            status: 'disconnected',
            ticker : ftse100Tickers.tickers[randomInt],
            twitter : ftse100Tickers.twitter[randomInt]
        }

    }

    componentWillMount(){
        this.socket = IO(location.protocol + "//" + document.domain + ":" + location.port);
        this.socket.on("connect", (() => this.connect()));
        this.socket.on("disconnect", (() => this.disconnect()));
        this.socket.on("initial data", ((data) => this.createInitialChart(data)));
    }

    connect(){
        this.setState({status: 'connected'});
        this.socket.emit("get initial data", this.state.ticker);
    }

    disconnect(){
        this.setState({status: 'disconnected'})
    }

    createInitialChart(data) {
        const volumeChart = this.state.volumeChart;

        const newVolumeChart = {...volumeChart};


        newVolumeChart.labels = App.getTimeSeries(data);
        newVolumeChart.datasets[0].data = data.map(row => row.volume);

        this.setState({ volumeChart: newVolumeChart })
    }

    handleNavClick(url) {
        fetch(url)
            .then((response) => response.text())
            .then((text) => this.setState({ticker: text}));
    }

    render() {
        return (
            <div>
                <NavBar/>
                <div className="container-fluid">
                    <div className="row">
                        <NavBarSide clickHandler={(url) => this.handleNavClick(url)}/>
                        <Dashboard
                            volumeChart={this.state.volumeChart}
                            ticker={this.state.ticker}
                            twitter={this.state.twitter}
                            status={this.state.status}
                        />
                    </div>
                </div>
            </div>
        )
    }
}


render(<Router><App/></Router>, window.document.getElementById("root"));

【问题讨论】:

  • 查看 componentWillRecieveProps()

标签: javascript reactjs


【解决方案1】:

如果我正确理解您的问题,我认为这样的事情会起作用:

initSocket() {
    this.socket = IO(location.protocol + "//" + document.domain + ":" + location.port);
    this.socket.on("connect", (() => this.connect()));
    this.socket.on("disconnect", (() => this.disconnect()));
    this.socket.on("initial data", ((data) => this.createInitialChart(data)));
}

componentWillMount() {
    this.initSocket();
}

componentWillUpdate(prevState, nextState) {
    if(prevState.ticker !== nextState.ticker)
        this.initSocket();
}

来自React docs

componentWillUpdate() 在接收新道具或状态时在渲染之前调用。以此为契机,在更新发生之前进行准备。初始渲染不调用此方法。

【讨论】:

  • 啊,看起来很不错。
  • 这似乎在实现时创建了多个连接
  • 什么意思?我以为你想在每次更改代码时创建一个新套接字?
【解决方案2】:

试试ComponentWillReceiveProps()

【讨论】:

  • 再拨打this.componentWillMount()会不会错?
  • 我试过了,不行,componentWillMount()只在render()之前运行一次
猜你喜欢
  • 2020-06-19
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2012-03-03
相关资源
最近更新 更多