gpt4 book ai didi

javascript - 无法使用静态数据在 react 应用程序中执行动态搜索

转载 作者:行者123 更新时间:2023-11-30 14:24:58 26 4
gpt4 key购买 nike

我在我的 React 应用程序上执行排序、过滤和分页,它显示来自包含电影数据的 json 文件的数据。我能够从输入框中获取数据,但无法设置状态,也无法控制台日志 searchKey 和电影。

下面是 App.js 和 Hello.js 的代码。 App 组件同时具有排序和搜索功能。

App.js

import data from './data.json';

class App extends Component {
constructor() {
super();
this.state = {
movies: data.movies, sort_term: '', searchKey: '', filterList: '',
};
this.onSorting = this.onSorting.bind(this);
this.onSearchMovie = this.onSearchMovie.bind(this);
}
onSorting = (e) => {
let term = 'Title';
let option = e.target.value;
let sortedList = [...this.state.movies].sort((a, b) => {
return (option == 'asc' ? (a[term] <= b[term] ? -1 : 1) :
(a[term] >= b[term] ? -1 : 1))
});
this.setState({ sort_term: term });
this.setState({ movies: sortedList });
}
onSearchMovie(e) {
let key = e;
console.log(key);
this.setState({searchKey : key });
console.log(searchKey);
let list = movies.filter(m =>{
return m.Title.toLowerCase().includes(searchKey.toLowerCase());
});
this.setState({movies:list});
}
render() {
const { movies } = this.state;

if (!movies.length) {
return (
<div className="container">
<h2>loading...</h2>
</div>
);
}
else {
return (
<div>
<Hello sort_term={this.state.sort_term}
onSorting={this.onSorting}
onSearch={this.onSearchMovie} />
<br />
<Table movies={this.state.movies} />
</div>
);
}
}
}

Hello.js

class Hello extends Component {
constructor(props) {
super(props);
this.state = { inputField: '', }
this.onSubmitTitle = this.onSubmitTitle.bind(this);
this.getTitle = this.getTitle.bind(this);
}
onSubmitTitle(e){
e.preventDefault();
this.props.onSearch(this.state.inputField);
this.setState({ inputField: '' });
}
getTitle(e){
this.setState({ inputField: e.target.value });
// console.log('---');
// console.log(this.state.inputField);
}

render() {
const { sort_term, onSorting } = this.props;

return (
<div className="header">
Database
<ul className="navLeft">
<li>
<form onSubmit={this.onSubmitTitle}>
<input type="search" onChange={this.getTitle} value={this.state.inputField}
className="search-bar"
placeholder="Type for search..." />
</form>
</li>
<li >
<form >
<select
onChange={onSorting}
className="searchBar">
<option value="desc" >Sort Title(Z - A)</option>
<option value="asc">Sort Title(A - Z)</option>
<option value="descDirector">Sort Director(Z - A)</option>
<option value="ascDirector">Sort Director(A - Z)</option>
</select>
</form>
</li>
</ul>
</div>
);
}
}

最佳答案

你有几个问题:

  • 这里有一些 undefined variable :

            onSearchMovie(e) {
    let key = e;
    console.log(key);
    this.setState({ searchKey: key });
    console.log(searchKey);
    let list = movies.filter(m => {
    return m.Title.toLowerCase().includes(searchKey.toLowerCase());
    });
    this.setState({ movies: list });
    }

    like `searchKey` and `movies`.
  • setState 是异步的,所以这样做:

            this.setState({ sort_term: term });
    this.setState({ movies: sortedList });

    Is the same as doing this:


    this.setState({
    sort_term: term,
    movies: sortedList
    });
  • 话虽如此,此代码块可能无法按预期工作:

        onSearchMovie(e) {
    let key = e;
    console.log(key);
    this.setState({ searchKey: key });
    console.log(searchKey);
    let list = movies.filter(m => {
    return m.Title.toLowerCase().includes(searchKey.toLowerCase());
    });
    this.setState({ movies: list });
    }

    因为如上所述,setState是异步的。所以 this.state.searchKey 可能不是你在下一行访问它时的想法。
    使用 key 变量或使用将在 setState 完成后触发的 setState 回调。

    this.setState({someKey: someValue}, () => {console.log(this.state.someKey)})

    您可以在文档中阅读更多相关信息 Why is setState giving me thewrong value? .

  • 您可能不知道的另一件事是,当您在
    上使用 onSubmitform 您实际上需要触发提交。既然你没有您可以使用 enter 键完成任何提交按钮。所以当你
    专注于 inputenter 键,form 将提交。

  • 我会做的另一件事是显示和更新 filteredMovis直接列出而不是 movies 列表,因为一旦你过滤取出元素,然后您将无法取回它们。所以当你过滤你的时候在 movies 上执行此操作,但不更新 filteredMovis 列表从原始 movies 列表中删除项目。

这是一个工作和运行的例子:

const data = {
movies: [
{
id: 1,
Title: "wonder woman"
},
{
id: 2,
Title: "kill bill"
},
{
id: 3,
Title: "world war z"
},
{
id: 4,
Title: "pixels"
}
]
};

class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { inputField: "" };
this.onSubmitTitle = this.onSubmitTitle.bind(this);
this.getTitle = this.getTitle.bind(this);
}
onSubmitTitle(e) {
e.preventDefault();
this.props.onSearch(this.state.inputField);
this.setState({ inputField: "" });
}
getTitle(e) {
this.setState({ inputField: e.target.value });
// console.log('---');
// console.log(this.state.inputField);
}

render() {
const { onSorting } = this.props;

return (
<div className="header">
Database
<ul className="navLeft">
<li>
<form onSubmit={this.onSubmitTitle}>
<input
type="text"
onChange={this.getTitle}
value={this.state.inputField}
className="search-bar"
placeholder="Type for search..."
/>
</form>
</li>
<li>
<form>
<select onChange={onSorting} className="searchBar">
<option value="desc">Sort Title(Z - A)</option>
<option value="asc">Sort Title(A - Z)</option>
<option value="descDirector">Sort Director(Z - A)</option>
<option value="ascDirector">Sort Director(A - Z)</option>
</select>
</form>
</li>
</ul>
</div>
);
}
}

class App extends React.Component {
constructor() {
super();
this.state = {
movies: data.movies,
filteredMovis: data.movies,
sort_term: "",
searchKey: "",
filterList: ""
};
this.onSorting = this.onSorting.bind(this);
this.onSearchMovie = this.onSearchMovie.bind(this);
}
onSorting = e => {
let term = "Title";
let option = e.target.value;
let sortedList = [...this.state.movies].sort((a, b) => {
return option == "asc"
? a[term] <= b[term]
? -1
: 1
: a[term] >= b[term]
? -1
: 1;
});
this.setState({
sort_term: term,
filteredMovis: sortedList
});
};
onSearchMovie(key) {
const { movies } = this.state;
let list = movies.filter(m => {
return m.Title.toLowerCase().includes(key.toLowerCase());
});
this.setState({ filteredMovis: list, searchKey: key });
}
render() {
const { filteredMovis, movies } = this.state;

if (!movies.length) {
return (
<div className="container">
<h2>loading...</h2>
</div>
);
} else {
return (
<div>
<Hello
sort_term={this.state.sort_term}
onSorting={this.onSorting}
onSearch={this.onSearchMovie}
/>
<br />
{filteredMovis.map(movie => <div key={movie.id}>{movie.Title}</div>)}
</div>
);
}
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

关于javascript - 无法使用静态数据在 react 应用程序中执行动态搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com