我是新來的反應和制作一個小應用程式來學習圖書館和思維方式。
但是我遇到了一個讓我完全跺腳的問題......
我有包含任務串列的根組件。我將這些任務傳遞給自定義組件,以將它們呈現為如下所示的組:包含所有當前任務的陣列
<TasksView tasks={this.state.tasks}></TasksView>
在哪里。this.state.tasks
但問題是我的TaskView組件似乎從來沒有收到這些任務......
完整代碼見下文:
根:
class App extends Component<{}, IAppState> {
constructor(props: any) {
super(props);
this.state = {
taskCategories: [],
tasks: [],
currentTask: {}
};
}
testing() {
this.setState((prev: IAppState) => {
return {
tasks: [...prev.tasks, {
index: 0,
timespan: [TimeTypes.Day, TimeTypes.Week, TimeTypes.Month, TimeTypes.Year][Math.round(Math.random() * 9)],
name: '',
repeatAmount: 0,
repeatDelay: 0,
category: {
id: 0,
color: "",
name: ""
},
onComplete: function (index: number): void {
throw new Error('Function not implemented.');
}
}]
}
});
}
render() {
console.log("tasks count in parent: ", this.state.tasks.length); //<-- console.log A
return (
<SafeAreaView style={styles.container}>
<TasksView tasks={this.state.tasks}></TasksView>
<TouchableOpacity
onPress={this.testing.bind(this)}
style={styles.createTask}
>
</TouchableOpacity>
</SafeAreaView>
)
}
};
任務視圖:
class TasksView extends Component<TasksViewProps, any> {
taskGroups: TasksGroupData[];
stickyIndices: number[];
constructor(props: TasksViewProps) {
super(props);
console.log("props should be updated..."); //<-- console.log B
console.log(props.tasks.length); //<-- console.log C
this.taskGroups = [];
this.stickyIndices = [];
}
render(): ReactNode {
return [
<Text style={tasksViewStyle.title}>Your Goals</Text>,
<ScrollView
stickyHeaderIndices={this.stickyIndices}
showsVerticalScrollIndicator={false}
style={tasksViewStyle.scrollView}
>
{this.taskGroups.map((group: TasksGroupData, index: number) =>
<TasksGroup key={index} timespan={group.timespan} tasks={group.tasks}></TasksGroup>
)}
</ScrollView>
];
}
}
我省略了所有介面定義和一些輔助函式,因為它們與手頭的問題無關。
So what i would expect is every time console.log A gets executed console.log B and C would also be executed but this is not the case.
See here a screenshot of current console.log sequence.

If any additional information is required let me know so I can update the question.
uj5u.com熱心網友回復:
constructor僅在您的組件首次掛載時運行一次,因為 React 在組件的生命周期內重復使用相同的類實體(請參閱這些檔案)。這就是為什么您在最初運行一次后看不到日志呼叫的原因。
對于在每個渲染上運行的日志記錄,您可以將console.logs 移動到componentDidUpdate中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414481.html
標籤:
上一篇:角度切換按鈕未按預期作業
