我想知道是否有人可以帮助我解决这个问题,因为我是 react-native 和 redux 的新手。
我想只用一个名字填充一个 FlatList,我正在使用这个类(显然还有其他类(:
操作.js
const LOAD_CLIENT = 'LOAD_CLIENT';
export async function loadClient() {
const client = await Parse.Query("Client");
return {
type: LOAD_CLIENT,
client: client,
};
}
减速器.js
import { LOAD_CLIENT } from '../actions'
const initialState = {
objectId: null,
name: null,
};
function client(state: State = initialState, action: Action): State {
if (action.type === LOAD_CLIENT) {
let {objectId, name} = action.client; // de-structuring action data
return {
objectId,
name,
};
}
return state;
}
module.exports = client;
列表屏幕.js
import {
loadClient
} from './actions'
class SettingsScreen extends Component {
render() {
return (
<View style={styles.container}>
<FlatList style={styles.listStyle}
data={this.props.client}
renderItem={({item}) => <Text>{item.name}</Text>}
/>
</View>
)
}
}
export default SettingsScreen
我需要什么才能用 client.name 填充列表?我遵循了 Redux 基础知识来到达这里,但现在我被卡住了。
请在您的文件中更改类似内容的内容。
减速器.js
import { LOAD_CLIENT } from '../actions'
const initialState = {
data: null,
};
function client(state: State = initialState, action: Action): State {
if (action.type === LOAD_CLIENT) {
return Object.assign({}, state, {
data: action.client
});
}
return state;
}
module.exports = client;
列表屏幕.js
import { loadClient } from './actions'
import { connect } from 'react-redux';
class SettingsScreen extends Component {
constructor(props){
super(props);
this.state={
client: null,
}
}
componentDidMount(){
this.props.loadClientData();
}
componentWillReceiveProps(nextProps) {
if (nextProps.data != null) {
this.setState({
client: nextProps.data
});
}
}
render() {
return (
<View style={styles.container}>
<FlatList style={styles.listStyle}
data={this.state.client}
renderItem={({item}) => <Text>{item.name}</Text>}
/>
</View>
)
}
}
const mapStateToProps = (state) => ({
data: state.reducers.data
});
const mapDispatchToProps = (dispatch) => ({
loadClientData: () => dispatch(loadClient())
})
export default connect(mapStateToProps, mapDispatchToProps)(SettingsScreen)
或者您可以参考此链接进行练习。
https://medium.com/@imranhishaam/advanced-redux-with-react-native-b6e95a686234
您忘记连接组件。
import {connect} from 'react-redux;
{...}
const mapStateToProps = ({reducerName})=>{
const {name, objectId} = reducerName;
return {name, objectId}
}
在此名称之后,对象 ID 将在组件 props 上可用。但请记住,flatList 数据需要一个数组,因此您的化简器应该有一个变量 client:[],它将在获取时填充所有数据。如果只传递一个对象,平面列表将不起作用,您需要传递一个对象数组