我想知道是否有人可以帮我解决这个问题,因为我是新手本地和redux。
我想用一个名字填充FlatList,我正在使用这些类(显然还有其他类):
actions.js
const LOAD_CLIENT = 'LOAD_CLIENT';
export async function loadClient() {
const client = await Parse.Query("Client");
return {
type: LOAD_CLIENT,
client: client,
};
}
reducers.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;
listScreen.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的基础来到这里,但现在我被卡住了。
答案 0 :(得分:1)
请在您的文件中更改此类内容。
reducer.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;
listScreen.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
答案 1 :(得分:0)
您忘记连接组件了。
import {connect} from 'react-redux;
{...}
const mapStateToProps = ({reducerName})=>{
const {name, objectId} = reducerName;
return {name, objectId}
}
此名称和objectId将在组件道具上可用。 但请记住,flatList数据需要一个数组,因此你的reducer应该有一个变量客户端:[]将在fetch中填充所有数据。 如果你只传递一个对象,你需要传递一个对象数组
,否则flatlist不会工作