Rails和ReactJS -重新渲染组件

Rails and ReactJS - Re-rendering component

本文关键字:新渲染 组件 -重 ReactJS Rails      更新时间:2023-09-26

所以我仍然在玩Todo应用程序,以学习Reactjs。该应用程序非常简单,用户可以添加新任务并将其标记为已完成。

我在后端使用Rails,使用react-rails gem,并尝试了不同的方法来处理创建新任务或刚刚更新时的组件重新渲染。

而不是在给定的时间间隔从服务器获取数据,我渲染JSON与所有的任务从后端每次创建或更新一个新任务。

我想知道这是否是最优化的方法。这是我的Rails控制器:

class TasksController < ApplicationController
	before_filter :get_tasks
	def get_tasks
		@tasks = Task.where('iscompleted is null').order(created_at: :desc)
	end
	def index
		render :json => @tasks
	end
	def create
		@task = Task.create(task_params)
		render :json => @tasks
	end
	def update
		@task = Task.update(params[:id], task_params)
		render :json => @tasks
	end
	private
	def task_params
		params.require(:task).permit(:id, :name, :iscompleted)
	end
end

这是我的ReactJS组件:

var TodoBox = React.createClass({
	loadTasksFromServer: function() {
		$.ajax({
			url: this.props.url,
			dataType: 'json',
			cache: false,
			success: function(data) {
				this.setState({data: data.tasks});
			}.bind(this)
		});
	},
	handleTaskSubmit: function(task) {
		$.ajax({
			url: this.props.url,
			dataType: 'json',
			type: 'POST',
			data: {task},
			success: function(data) {
				this.setState({data: data.tasks});
			}.bind(this),
			error: function(xhr, status, err) {
				console.error(this.props.url, status, err.toString());
			}.bind(this)
		});		
	},
	handleTaskCompleted: function(task) {
		$.ajax({
			url: '/task/' + task.id,
			dataType: 'json',
			type: 'PATCH',
			data: {task},
			success: function(data) {
				this.setState({data: data.tasks});
			}.bind(this),
			error: function(xhr, status, err) {
				console.error(this.props.url, status, err.toString());
			}.bind(this)
		});
		
	},
	getInitialState: function() {
		return {
			data: []
		};
	},
	componentDidMount: function() {
		this.loadTasksFromServer();
	},
	render: function() {
		return (
			<div className="todoBox">
			<div className="container-fluid col-md-6 col-md-offset-3">
			<TodoForm onTaskSubmit={this.handleTaskSubmit}/>
			<TodoList onTaskCompleted={this.handleTaskCompleted} data={this.state.data}/>
			
			</div>
			
			</div>
			);
	}
});

这个方法很有效,但我在这里学习,所以每一个评论或建议将非常感谢。

谢谢

我发现在React中过滤结果更有效,因为它不需要从后端呈现所有任务。因此,我只从rails后端呈现新对象或更新对象,如下所示:

class TasksController < ApplicationController
def index
    @tasks = Task.all
    render :json => @tasks
end
def create
    @task = Task.create(task_params)
    render :json => @task
end
def update
    @task = Task.update(params[:id], task_params)
    render :json => @task
end

private
def task_params
    params.require(:task).permit(:id, :name, :iscompleted)
end

因此React组件看起来像这样:

var TodoBox = React.createClass({
loadTasksFromServer: function() {
    var rawData = [];
    $.ajax({
        url: this.props.url,
        dataType: 'json',
        cache: false,
        success: function(data) {
            this.setState({data: data.tasks});
        }.bind(this)
    });
},

handleTaskSubmit: function(task) {
    $.ajax({
        url: this.props.url,
        dataType: 'json',
        type: 'POST',
        data: {task},
        success: function(data) {
            this.state.data.push(data.task);
            this.setState({data: this.state.data});
        }.bind(this),
        error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
        }.bind(this)
    });     
},
handleTaskCompleted: function(task) {
    $.ajax({
        url: '/task/' + task.id,
        dataType: 'json',
        type: 'PATCH',
        data: {task},
        success: function(data) {
            task.iscompleted = data.task.iscompleted;
            this.setState({data: this.state.data});
        }.bind(this),
        error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
        }.bind(this)
    });
},
getInitialState: function() {
    return {
        data: []
    };
},
componentDidMount: function() {
    this.loadTasksFromServer();
},
render: function() {
    return (
        <div className="todoBox">
        <div className="container-fluid col-md-6 col-md-offset-3">
        <TodoForm onTaskSubmit={this.handleTaskSubmit}/>
        <TodoList onTaskCompleted={this.handleTaskCompleted} data={this.state.data}/>
        </div>
        </div>
        );
}

});

然后我在TodoList组件中过滤结果,然后再显示它们