我正在尝试使用ramda
进行过滤。我已经详细阅读了Ramda文档。使用Ramda和React设置状态
但是,我试图过滤它对我的setState
以及控制台日志没有任何影响。
直播代码示例:
https://codesandbox.io/s/qY219X102
我尝试:
import React from 'react';
import { render } from 'react-dom';
import R from 'ramda';
const o = {
movies: [
{ name: 'movie 1', genres: ['comedy', 'action'] },
{ name: 'movie 2', genres: ['action', 'drama'] },
{ name: 'movie 3', genres: ['drama', 'action'] },
],
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: o,
};
}
getGenre =() => {
R.pipe(
R.prop(o.movies),
R.filter(
R.and(
R.propSatisfies(R.find(R.equals('action')), 'genres'),
R.propSatisfies(R.find(R.equals('comedy')), 'genres'),
),
),
);
this.setState({ o });
console.log('genre', o);
};
render() {
const rawmovies = Object.keys(o).map(e => o[e]);
const movies = [].concat.apply([], rawmovies);
return (
<div>
<button onClick={this.getGenre}>Action genre</button>
{movies.map(e => <span key={e.name}> {e.name}</span>)}
</div>
);
}
}
render(<App />, document.getElementById('root'));
谢谢你,更加整洁。如何在嵌套时获得“流派”的价值? EG:'类型:[{name:'Movie',type:1},{name:'Adventure',type:2}],},'? – Ycon
我可能会这样做:'R.where({genres:R.pipe(R.pluck('name'),R.contains('drama'))}',或者将它解压缩到一个函数中,这样我可以写'R.where({genres:hasType('drama')})'。这不是最有效的代码,但是我只会担心它会导致问题。 –
我尝试了第一个选项,但没有成功,我把它放在一个codepen中向你展示 - https://codesandbox.io/s/DkNzqx7Wn – Ycon