如何将已更改状态发送到react-native中的组件?

时间:2018-06-03 08:50:57

标签: reactjs react-native react-redux

我是反应初学者&反应母语。 我使用反应16,反应 - 反应,反应 - 还原。

我正在尝试从firestore获取已经创建的类别。 首先,我使用action拨打connect(),然后,我使用thunk键入action,同时从firestore获取数据。 最后,我在reducer中返回了新的状态。 当然,我不知道还原过程,所以请提供一些提示。

这是我的代码。谢谢。

CategoryImageList.js(组件)

...

class CategoryImageList extends Component {
  componentWillMount() {
    this.props.getCategory();
  }

  renderImages() {
      return this.state.categories.map(category =>
          <CategoryImageCard key={category.imgName} category={category}/>
      );
  }

  render() {
    return (
        <ScrollView>
            {/*{this.renderImages()}*/}
        </ScrollView>
    );
  }
}

export default connect(null, {getCategory})(CategoryImageList);

category.js(行动)

...
export const getCategory = () => {
  return (dispatch) => { //using redux-thunk here... do check it out
    getCategories()
        .then(querySnapshot => {
            const test = [];
            querySnapshot.forEach((doc) => {
                test.push(
                {
                    imgName : doc.data()['imgName'],
                    name : doc.data()['name']
                });
            });

            dispatch({ type: GET_CATEGORY, payload: test} );
        });
  };
};

CategoryReducers.js(reducer)

...

const categoryInitialState = {
  name: [],
  imgName: []
}

export const CategoryReducer = (state = categoryInitialState, action) => {
  switch (action.type) {
    case GET_CATEGORY:
        console.log(action);
        return { ...state, categoryImg: {
            name: action.payload.name,
            imgName: action.payload.imgName
        }};

    default:
        return state;
    }
}

App.js

...
type Props = {};
export default class App extends Component<Props> {
    render() {
        const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
        return (
        <Provider store={store}>
            <View style={{flex:1}}>
                <Header headerText={'FoodUp'}/>
                <CategoryImageList />
            </View>
        </Provider>
    );
  }
}

减速器/ index.js

import { combineReducers } from 'redux';
import { CategoryReducer } from './CategoryReducer';

export default combineReducers({
    categories: CategoryReducer
});

已更新 Firebase.js

const config = {
  ...
};

firebase.initializeApp(config);
const db = firebase.firestore();
const storage = firebase.storage();
const settings = {timestampsInSnapshots: true};
db.settings(settings);

export const getCategories = () => {
  return db.collection('categories').get();
}

export const getCategoryImg = (categoryName, imgName) => {
  const ref = storage.ref(`category/${categoryName}/${imgName}`);
  return ref.getDownloadURL();
}

2 个答案:

答案 0 :(得分:1)

您必须将mapstateToProps添加到您的连接中,

const mapStateToProps = (state: any) => {
  return {
    name: state.categories.name,
    imageName:state.categories.imageName
  };
}

export default connect(mapStateToProps)(CategoryImageList)

然后,您将能够访问名称和图像名称,如, this.props.namethis.props.imageName

编辑:要发送GET_CATEGORY,您可以使用mapDispatchToProps或执行getCategory并从组件中调度,例如,

import {getCategory} from './category'

 componentWillMount() {
    this.props.getCategory(this.props.dispatch);
  }

并将getCategory函数更改为

export const getCategory = (dispatch) => {
...
dispatch({ type: GET_CATEGORY, payload: test} );
...
}

答案 1 :(得分:0)

mapStateToProps将Store状态作为参数/ param(由react-redux :: connect提供),并用于将组件与存储状态的特定部分链接。在你的情况下,你可以像这样使用。并且您可以在组件中使用name,imgName作为道具

const mapStateToProps = ({categories}) => {
    const { name, imgName } = categories;
    return {name, imgName};
};
export default connect(mapStateToProps, {getCategory})(CategoryImageList);