Javascript 在React中哪个元素应该处理数据?

Javascript 在React中哪个元素应该处理数据?,javascript,reactjs,Javascript,Reactjs,例如,有两个组件: class App extends React.Component { state = { comments=[1, 2, 3, 4] } render() { return ( <Comments /> ) } } class Comments extends React.Component { render() { return ( /* show comments */

例如,有两个组件:

class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}
类应用程序扩展了React.Component{
状态={
评论=[1,2,3,4]
}
render(){
返回(
)
}
}
类注释扩展了React.Component{
render(){
返回(
/*显示评论*/
)
}
}

我只想展示一些甚至是评论。我应该将排序功能放入应用程序并将准备好的数组发送给注释,还是发送整个数组并让注释自行排序?

这是一个设计决策。但是通常视图应该只显示模型而不显示任何逻辑。这意味着您的父组件应用程序应该过滤注释。

这是一个设计决策。但是通常视图应该只显示模型而不显示任何逻辑。这意味着您的父组件应用程序应该过滤注释。

这取决于您希望注释组件如何反应。如果要执行的功能不多,并且您希望让应用程序组件作为容器进行反应,并将注释作为受控组件,那么您可以这样做:

import React from "react";

class Comments extends React.Component {
  render() {
    const { comments } = this.props;
    return comments.map(comment => <h1>{comment}</h1>);
  }
}

class App extends React.Component {
  state = {
    comments: [1, 2, 3, 4]
  };
  render() {
    const { comments } = this.state;
    let evenComments = comments.filter(item => item % 2 === 0);
    return <Comments comments={evenComments} />;
  }
}

export default App;
从“React”导入React;
类注释扩展了React.Component{
render(){
const{comments}=this.props;
返回comments.map(comment=>{comment});
}
}
类应用程序扩展了React.Component{
状态={
评论:[1,2,3,4]
};
render(){
const{comments}=this.state;
让evenComments=comments.filter(项=>项%2===0);
返回;
}
}
导出默认应用程序;

这取决于您希望注释组件的反应方式。如果要执行的功能不多,并且您希望让应用程序组件作为容器进行反应,并将注释作为受控组件,那么您可以这样做:

import React from "react";

class Comments extends React.Component {
  render() {
    const { comments } = this.props;
    return comments.map(comment => <h1>{comment}</h1>);
  }
}

class App extends React.Component {
  state = {
    comments: [1, 2, 3, 4]
  };
  render() {
    const { comments } = this.state;
    let evenComments = comments.filter(item => item % 2 === 0);
    return <Comments comments={evenComments} />;
  }
}

export default App;
从“React”导入React;
类注释扩展了React.Component{
render(){
const{comments}=this.props;
返回comments.map(comment=>{comment});
}
}
类应用程序扩展了React.Component{
状态={
评论:[1,2,3,4]
};
render(){
const{comments}=this.state;
让evenComments=comments.filter(项=>项%2===0);
返回;
}
}
导出默认应用程序;

您可以在
APP.jsx
文件中拥有排序逻辑

像这样
类应用程序扩展了React.Component{
状态={
评论=[1,2,3,4]
}
render(){
返回(
注释%2==0)}/>
)
}
}
类注释扩展了React.Component{
render(){
返回(
/*显示评论*/
)
}

}
您可以在
APP.jsx
文件中拥有排序逻辑

像这样
类应用程序扩展了React.Component{
状态={
评论=[1,2,3,4]
}
render(){
返回(
注释%2==0)}/>
)
}
}
类注释扩展了React.Component{
render(){
返回(
/*显示评论*/
)
}

}
这在很大程度上取决于您为什么要这样过滤它。这在很大程度上取决于您为什么要这样过滤它。我认为OP是在征求代码设计建议,而不是如何实际实现它。@goto1谢谢,我没有仔细阅读问题陈述,现在更新了我的答案。我认为OP是在询问代码设计建议,而不是如何实际实现它。@goto1谢谢,我没有彻底阅读问题陈述,现在更新了我的答案。