考虑使用react-redux的react-native应用程序中的以下3个JS文件(index.js、actions.js和reducer.js)。
index.js
import React, {Component} from 'react';
import {View, Text, ActivityIndicator} from 'react-native';
import {connect} from 'react-redux';
import {onSetup} from './actions';
class Scene01 extends Component {
componentWillMount() {
// dataFromOtherScene EXISTS when this Scene is created!
// It is an OBJECT;
this.props.onSetup(this.props.dataFromOtherScene);
}
render () {
console.log('R', this.props);
if ((this.props.paths) && (this.props.reference) && (this.props.current >= 0)) {
const processedData = this.props.reference[Object.keys(this.props.reference)[0]].data;
const currentPath = this.props.path[this.props.current];
const pathData = processedData.steps[currentPath[1]].questions[currentPath[2]];
return (
<View>
<Text>{currentPath.title}</Text>
<Text>{pathData.anyProperty}</Text>
<Text>{pathData.anotherProperty}</Text>
</View>
);
} else {
return (
<ActivityIndicator size='large' />
);
}
}
}
const mapStateToProps = (state) => {
return {
...state.Scene01Reducer,
dataFromOtherScene: state.OtherScene.data
};
};
export default connect(mapStateToProps, {
onSetup
})(Scene01);
actions.js
export const ON_SETUP_SUCCESS_ACTION = 'D8129820-723B-42CE-9C2D-EA0524919E89';
export const onSetup = (data) => {
const paths = [];
const reference = data.reference[Object.keys(data.reference)[0]].steps;
const steps = Object.keys(reference);
for (let s = 0; s < steps.length; s++) {
const step = reference[steps[s]];
const path = [step.title, steps[s]];
const questions = Object.keys(step.questions);
for (let q = 0; q < questions.length; q++) {
const fullpath = [...path, questions[q]];
paths.push(fullpath);
}
}
return {
type: ON_SETUP_SUCCESS_ACTION,
payload: {paths, reference}
};
};
reducer.js
import {ON_SETUP_SUCCESS_ACTION} from './actions';
/**
* Default State
*/
const DEFAULT_STATE = {
current: null,
paths: null,
reference: null
};
/**
* Reducer Body
*/
export default (state = DEFAULT_STATE, action) => {
switch (action.type) {
case ON_SETUP_SUCCESS_ACTION:
return {...state, paths: action.payload.paths, reference: action.payload.reference, current: 0};
default:
return state;
}
};
我尝试了很多方法...构造函数、componentWillReceiveProps、componentShouldUpdate,但是在react-redux更新状态之后(return {type: ON_SETUP_SUCCESS_ACTION, payload: {paths, reference}};
),再次调用 render 方法,但 } else {
语句保持渲染。
console.log('R', this.props);
显示第一次为 3 个 reducer 属性调用null:paths、引用和当前。
第二次,在reducer更新之后,控制台显示这3个属性设置正确...但是组件没有更新...不重新渲染。
最佳答案
您完全确定您的 if 具有真实值吗?
(this.props.paths) && (this.props.reference) && (this.props.current >= 0) 这可能为 false,并且 else 语句将始终呈现。
如果是,您可以尝试使用生命周期方法,例如 componentWillMount 或 componentWillUpdate。
此外,我认为您应该使用 mapStateToProps 来发送路径、引用和当前作为 prop。
关于javascript - 如何在不直接在 JSX 中使用 props 或 state 的情况下强制组件重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43215147/