我是 ReactJs 的新手,并试图遵循最佳实践。根据我的研究,我遇到了几篇相互矛盾的文章,讨论了应该如何实现。
状态是否应该依赖于从父组件传递下来的属性?在下面的比较中,它们都遵循 SRP,但不确定哪个是最好的。希望得到您的建议,谢谢!
1. -- React.js 中组件状态的最佳实践
首先,可能也是最重要的一点,组件的状态不应依赖于传入的 props。(请参阅下面的示例,了解我们不应该做什么)
class UserWidget extends React.Component {
// ...
// BAD: set this.state.fullName with values received through props
constructor (props) {
this.state = {
fullName: `${props.firstName} ${props.lastName}`
};
}
// ...
}
2. --一个可靠的 React 组件的 7 个架构属性
让我们重构一个职责:渲染表单字段并附加事件处理程序。它应该不知道如何直接使用存储......组件从一个道具initialValue接收存储的输入值,并使用道具函数saveValue(newValue)保存输入值。这些 props 由 withPersistence() HOC 使用 props 代理技术提供。
class PersistentForm extends Component {
constructor(props) {
super(props);
this.state = { inputValue: props.initialValue };
}
// ...
}
3. -- 在我的情况下,我有类似以下的内容(想知道这是否是一个可接受的实现?) - 状态应该在 Tasks 中处理,还是在位于 TasksWithData 和 Tasks 之间的另一个 TasksWithPersistence 类型的组件中处理?
export default function TasksWithData(TasksComponent) {
return class withData extends React.Component {
render() {
const tasks = TaskAPI.getTasks();
return (
<TasksComponent
tasks={tasks}
{...this.props}
/>
)
}
}
}
export default class Tasks extends React.Component {
state = {
tasks: [],
addItemInput: null
};
// ...
componentDidMount() {
this.updateComponentState({tasks: this.props.tasks});
}
componentDidUpdate() {
this.prepUIForNextAddition();
}
// ...
}