React Native - TypeError:null 不是对象
2019-10-17
12166
我仍在学习 React Native,我正在尝试从 API 中检索数据并将其作为自定义单选按钮返回,但如果我调用 API,我会收到此错误:
null is not an object (evaluating 'this.props.activities.map')
{this.props.activities.map((val, index) => {
let { key, type, placeholder } = val;
if (type === "selection") {
var buttons = [];
placeholder.forEach((e, index) => {
var selectedButton = img.findButton(e, true);
var normalButton = img.findButton(e);
buttons.push(
<RadioButton
key={index}
value={e}
element={<Image source={selectedButton} />}
selectedElement={<Image source={normalButton} />}
onPress={() => this.changeSelection(key, e)}
selected={this.state[key]["value"]}
/>
);
});
var rows = [],
columns = [];
var i = 0;
buttons.forEach((e, index) => {
rows.push(e);
i++;
if (i === 2 || index === buttons.length - 1) {
//max buttons per row
i = 0;
columns.push(
<View key={index} style={{ flex: 1, flexDirection: "row" }}>
{rows}
</View>
);
rows = [];
i = 0;
}
});
return (
<View key={key} style={{ flex: 1, margin: normalize(20) }}>
{columns}
</View>
);
}
})}
'this.props.activites' 来自这个
let initialState = {
activities: null,
};
export default function mainReducer(state = initialState, action) {
switch (action.type) {
case t.RECEIVE_ACT:
return Object.assign({}, state, { actReceived: true, activities: action.activities });
case t.EMPTY_ACT:
return Object.assign({}, state, { actReceived: false, activities: null });
default:
return state;
}
}
我想知道它是怎么变成空的
3个回答
activities
的初始状态为
null
。因此,在您从 api 获得响应之前,React 会使用
null
值呈现代码的该部分。您可以将
activities: []
作为初始值,也可以在 map 函数之前检查它是否为 null,例如
{this.props.activities && this.props.activities.map((val, index) => {...
如果您要使用
activities: []
,那么您仍然可以在 map 之前进行检查,尽管它是可选的但仍然很好,例如;
{this.props.activities.length && this.props.activities.map((val, index) => {...
octobus
2019-10-17
this.props.activities
来自哪里?
它是异步的吗,因为它似乎在某个点为
null
。
如果添加以下行,您将不再看到此错误。
this.props.activities && this.props.activities.map(.....
Paul Fitzgerald
2019-10-17
Paul 的回答是万无一失的,但您也可以使用默认值来避免
虚假值
YourComponent.defaultProps = {
activities: []
}
tolotra
2019-10-17