[英]Testing a react component using custom hooks with crud operations functions
[英]React CRUD operations always using state
我正在使用altjs作為我的Flux實現來構建React應用程序。 當我嘗試從前端創建/刪除項目時,無論我將什么作為參數傳遞給create / delete函數,它總是以傳遞整個狀態結束。
例如:我正在嘗試刪除ID = 1的項目。 我在該項目上單擊刪除,然后僅將ID傳遞給組件中的刪除功能。 該函數再次通過ID調用刪除服務。 一旦到達存儲層,它就具有組件的整個狀態,而不僅僅是傳遞的ID。
我對React / Flux還是很陌生,不確定我做錯了什么或為什么會這樣。
主要組件刪除功能:
deleteItem = (id) => {
console.log(id) //logs out 56b36c34ad9c927508c9d14f
QuestionStore.deleteQuestion(id);
}
此時,id仍然只是id。
QuestionStore:
import alt from '../core/alt';
import QuestionActions from '../actions/QuestionActions';
import QuestionSource from '../sources/QuestionSource';
class QuestionStore {
constructor() {
this.bindActions(QuestionActions);
this.exportAsync(QuestionSource);
this.loaded = false;
this.modalIsOpen = false;
this.data = [];
this.question = {
"text": '',
"tag": [],
"answer": [],
"company": [],
"createdAt": ''
};
this.error = null;
this.questionAdded = null;
this.questionDeleted = null;
}
onGetQuestions(data) {
if (data === false) {
this.onFailed();
} else {
this.data = data;
this.loaded = true;
}
}
onCreateQuestion(response) {
if (response === false) {
this.onFailed();
} else {
this.questionAdded = response;
}
}
onDeleteQuestion(response) {
if (response === false) {
this.onFailed();
} else {
this.questionDeleted = response;
}
}
onFailed(err) {
this.loaded = true;
this.error = "Data unavailable";
}
}
export default alt.createStore(QuestionStore, 'QuestionStore');
QuestionSource:
import Api from '../services/QuestionApi';
import QuestionActions from '../actions/QuestionActions';
let QuestionSource = {
fetchData() {
return {
async remote(state) {
return Api.getQuestions()
},
success: QuestionActions.getQuestions
}
},
createQuestion(question) {
return {
async remote(question) {
return Api.createQuestion(question)
},
success: QuestionActions.createQuestion
}
},
deleteQuestion(id) {
//id here is an object of the entire state of QuestionStore
return {
async remote(id) {
return Api.deleteQuestion(id)
},
success: QuestionActions.deleteQuestion
}
}
};
export default QuestionSource;
一旦達到這一點,即使僅傳遞了id,id仍是組件的整個狀態。
綁定到操作的第一個參數是商店的狀態( exportAsync
調用結果的一部分。因此,所有參數都向右移動一個,調用函數所用的第一個參數又成為第二個參數。參見下面的代碼示例:
deleteQuestion(state, id) {
//state here is an object of the entire state of QuestionStore
//id will be the first argument you provide to the function.
return {
async remote(id) {
return Api.deleteQuestion(id)
},
success: QuestionActions.deleteQuestion
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.