🪁react/react 실습
키워드 제거 시, 검색폼 내용도 같이 지우기[제출 키워드를 false로]
하얀성
2024. 1. 3. 09:11
import store from "./js/Store.js";
class App extends React.Component {
constructor() {
super();
this.state = {
searchKeyword: "",
searchResult: [],
submitted: false,
};
}
handleSubmit(event) {
event.preventDefault();
this.search(this.state.searchKeyword);
}
search(searchKeyword) {
const searchResult = store.search(searchKeyword);
this.setState({
searchResult,
submitted: true,
});
}
handleReset() { // reset 버튼 누르면 동작하는 방식 정의
this.setState({
searchKeyword: "",
this.state.submitted : false // ================> 여기가 틀림
});
}
handleChangeInput(event) { // 검색어를 수동으로 지우면 검색폼 내용 삭제
const searchKeyword = event.target.value;
if(searchKeyword.length <= 0 && this.state.submitted) {
return this.handleReset()
}
this.setState({ searchKeyword });
}
render() {
const searchForm = (
<form
onSubmit={(event) => this.handleSubmit(event)}
onReset={() => this.handleReset()}
>
<input
type="text"
placeholder="검색어를 입력하세요"
autoFocus
value={this.state.searchKeyword}
onChange={(event) => this.handleChangeInput(event)}
/>
{this.state.searchKeyword.length > 0 && (
<button type="reset" className="btn-reset"></button>
)}
</form>
);
const searchResult =
this.state.searchResult.length > 0 ? (
<ul className="result">
{this.state.searchResult.map(({ id, imageUrl, name }) => (
<li key={id}>
<img src={imageUrl} />
<p>{name}</p>
</li>
))}
</ul>
) : (
<div className="empty-box">검색 결과가 없습니다</div>
);
return (
<>
<header>
<h2 className="container">검색</h2>
</header>
<div className="container">
{searchForm}
<div className="content">{this.state.submitted && searchResult}</div>
</div>
</>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"));
this.state.submitted: false 라고 해서 검색키워드가 없어지면, reset버튼을 눌렀을 때 메서드를 발생시켜서 submitted가 false가 되게끔. 근데 왜 답이 submitted: false인지 모르겠어 왜 this.state를 붙이는게 틀린 답인거지?
답:
문제가 되는 부분은 handleReset 메서드에서의 setState 호출입니다. React에서 setState를 사용하여 state를 변경할 때, 직접적으로 this.state를 수정해서는 안 됩니다. setState 함수는 새로운 상태 값을 전달받아 이를 현재의 state에 병합하는 방식으로 동작합니다. 여기서 this.state를 직접 참조하거나 수정하는 것은 React의 state 관리 철학에 어긋납니다.
this.state.submitted: false라는 표현은 JavaScript 객체의 속성을 정의하는 올바른 방식이 아닙니다. 객체 내에서 속성을 설정할 때는 key: value 형식을 사용해야 합니다. this.state라는 표현은 현재 컴포넌트의 상태 객체를 참조하는 것이며, 이를 직접 수정하는 대신 setState 함수를 통해 상태를 간접적으로 변경해야 합니다.